Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving variables outside of navigator.geolocation.getCurrentPosition? (javascript)

I'm trying to play with the scope of js to pull a variable out of navigator.geolocation.getCurrentPosition

var lat;
function callback (position) {
    lat = position.coords.latitude;
}
navigator.geolocation.getCurrentPosition(callback,fail,{timeout:10000});
// after getCurrentPosition succeeds
alert(lat); // this alerts null

The above code cannot store position.coords.latitude in the lat variable because of the scope. Is there a way to do this?

like image 699
Derek Avatar asked Mar 29 '12 23:03

Derek


1 Answers

You have to remember the async\ajax nature.

this is the execution order of your code:

var lat;
alert(lat); // this alerts null
navigator.geolocation.getCurrentPosition(callback,fail,{timeout:10000});
function callback (position) {
    lat = position.coords.latitude;
}

This why you get null. async!, async! :)

like image 118
gdoron is supporting Monica Avatar answered Oct 25 '22 03:10

gdoron is supporting Monica