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 prop
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.
// x is assigned in `onSuccess`
var x;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert(x); // will be undefined, the response is not processed yet
Think about it: getCurrentPosition
is 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. onSuccess
was not called yet when you alert x
.
Only solution:
All the code that has to access the position as to be in or called from the callback.
have you tried setting it via the global window
object?
//on Successful callback receives a Position Object
function onSuccess(position) {
var coords = position.coords;
window.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
}
also, since you return the coordinates from the success handler, is there not another way to get this value?
As described by Felix King, you cannot return a value from a callback and in your global variable variant, the variable will not be set until after the AJAX request completes and calls the callback (hence its name !).
Using a global variable you can solve your problem if you have some sort of processing loop, you can add this code to that loop to do what is required whenever the coord changes.
if (coord) // global variable has a new value
// process it
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
// then clear it
coord = null;
}
You can implement a helper method like flowing:
var LocationHelper = function() {};
LocationHelper.prototype.getLocation = function(callback) {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
function onSuccess(pos) {
callback({
pos: pos
});
}
function onError(message) {
callback({
message: message
});
}
};
put a console.log(x);
just after x=cords
to check the value (works on Chrome and FF with FireBug)
do that also just after the call of OnSuccess.
Also don't forget that there is asynchronous code in JS (if you use AJAX to get the position), maybe you just don't receive the answer when you check the value of x