Search code examples
javascriptvariablesgeolocationglobal

Not so global variable?


Global variables don't change when passed through the function, why?

var userLat = 0;
var userLong = 0;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    userLat = position.coords.latitude;
    userLong = position.coords.longitude;
  });
}
$("#loc").html(userLat + "<br>" + userLong);

Thanks in advance.


Solution

  • Because navigator.geolocation.getCurrentPosition is an asynchronous function (Just like an ajax call). Technically $("#loc").html(userLat + "<br>" + userLong); is executed before the response is available.