Here is a quick question, I have the following method within an object, why is it returning undefined?
var getGeoLocation = function() {
if (typeof(navigator.geolocation) != 'undefined') {
var test = navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
return(new google.maps.LatLng(lat, lng));
});
}
}
var testFunction = function() {alert(getGeoLocation()); // returns undefined?}
This is because
navigator.geolocation.getCurrentPositionis asynchronous. ThegetGeoLocationfunction returns before the anonymous callback function passed togetCurrentPositionhas been executed, and since thegetGeoLocationfunction has noreturnstatement, it returnsundefined.Move code that depends on the response from
navigator.geolocation.getCurrentPositioninside the callback.