I am trying to write a function that returns an object representing the position of the device: I have tried:
function getDevicePosition () {
var positionObject;
if (isDeviceReady) {
navigator.geolocation.getCurrentPosition(function (position) {
positionObject = position;
console.log('location updated');
console.log(positionObject.coords.longitude);//1. works
}, function (err) {
console.log('Failed to get device position' + err);
return null;
});
} else {
warnUser();
return null;
}
console.log(positionObject.coords.longitude);//2. doesnt work as positionObject is null.
return positionObject;
}
Notice that I have added comments marking statement 1 and statement 2. If I initialized position object in statement 1. Why is it undefined in statement 2?
Because
getCurrentPositionis an asynchronous method. The line marked as2will run before the callback function gets a chance to execute, sopositionObjectwill still beundefined.You need to move all code that depends on
positionObjectinside the callback togetCurrentPosition.