My question is about Javascript.
I have a Callback function which receives a Position object on a successful callback.
The problem is that when I try to set the properties of the Position object to a global variable at a successful callback it just does not let me do it and the global just remains undefined.
As a workaround to that instead of directly setting the object properties to global variables i’m trying to return it through the callback function but I couldn’t find a way to set the return value of the callback function to a global variable.
Here’s the simplified code.
var x;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
//on Successful callback receives a Position Object
function onSuccess(position) {
var coords = position.coords;
x=coords; // Setting directly to an object does not work x still remains undefined after succesful callback
return coord; // Trying to set this to a global object
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
You can’t return a value from the callback (in this case). That would mean that inside of
getCurrentPosition, the return value from the callback has to be assigned somewhere.Assigning it to a global variable works, but at the time you access that variable, it was not assigned the new value yet. E.g.
Think about it:
getCurrentPositionis probably doing an Ajax request to get the position. Such a request takes (a) time (couple of milliseconds) and because of that (b) is asynchronous, which means that JavaScript does not wait until the response is received. Your code is way faster.onSuccesswas not called yet when you alertx.Only solution:
All the code that has to access the position as to be in or called from the callback.