0

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.

1 Answers1

0

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.

Nandan Bhat
  • 1,573
  • 2
  • 9
  • 21