Vlad T. Vlad T. - 1 year ago 47
Javascript Question

Can't set external (global?) variable when calculating geolocation

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

Answer Source

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.