6

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?

Derek
  • 11,980
  • 26
  • 103
  • 162

2 Answers2

2

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! :)

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • I see, so position.coords.latitude is indeed stored in lat? If so when, how can I transfer the data in lat to another variable? – Derek Mar 29 '12 at 23:34
  • @Derek. you call other function from `callback` wih the `lat` parameter. – gdoron Mar 29 '12 at 23:57
0

You can save your Position variable to input hidden field on document ready. After that, you can use jQuery to get back Geolocation value

Javscript:

<script>
var lat;
alert(lat); // this alerts null
navigator.geolocation.getCurrentPosition(callback,fail,{timeout:10000});
function callback (position) {
    jQuery('#pos_lat').val(position.coords.latitude);
}
</script>

HTML:

    <input hidden id='pos_lat' value='' /> 
    //value = position latitude on load

To get back value:

jQuery('#pos_lat').val();
  • To set `localStorage.setItem("pos_lat",position.coords.latitude);` to get `localStorage.getItem("pos_lat");` – San Apr 29 '16 at 12:32