1

Here is my code:

var lat;

$(document).ready(function() {
    navigator.geolocation.getCurrentPosition(function(position) {
        lat = position.coords.latitude;
        console.log("inside", lat);
    });

    console.log("outside", lat);
});

When I run it (see jsfiddle) the console shows this:

outside undefined
inside 55.8509728

Not sure if it matters, but I noticed that "outside" value is always displayed first even though it goes after the "inside" in the code.

Can someone be so kind to explain why I cannot get (or probably set?) that lat variable?

laurent
  • 88,262
  • 77
  • 290
  • 428
Vlad T.
  • 2,568
  • 3
  • 26
  • 40

1 Answers1

0

navigator.geolocation.getCurrentPosition is an async function, it's only going to call the function and thus run the "inside" code once it has retrieved the position. This is why you first see the "outside" message (at which point lat is indeed undefined) and then the inside message.

If you need to access the value of lat, you'll need to wait till it's defined, for example by calling another function from inside the getCurrentPosition callback.

laurent
  • 88,262
  • 77
  • 290
  • 428