I need help with JavaScript geolocation

I need help with JavaScript geolocation
0

#1

Hi! I try to save the latitude and longitude in an object. When I use console.log for the first time my variable contains the value of the latitude and longitude but in the second console.log, my value doesn’t appear. What is the problem? I read that it is for async programming but I don’t get it.
I read that from https://stackoverflow.com/questions/9935059/saving-variables-outside-of-navigator-geolocation-getcurrentposition-javascrip

$(document).ready(function(){
var userPosition = 
{
    lat: '',
    lon: ''
};

getLocation();

function getLocation()
{
    if(navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(function(position){
                userPosition.lat = position.coords.latitude;
                userPosition.lon = position.coords.longitude;
                console.log(userPosition.lat); //This works!
            });
        }
        else
        {
            alert("Geolocation not supported by your browser");
        }
}

console.log(userPosition.lat); // This not works

});


#2

The reason the last console.log doesn’t print any meaningful value is that, the function callback in getCurrentPosition is executed some time after the browser finishes executing your code. When you write callbacks, it’s better to think of them as functions that will run later (they are called back, so to speak). If you think of it that way, the lines

userPosition.lat = position.coords.latitude;
userPosition.lon = position.coords.longitude;
console.log(userPosition.lat);

are executed at some time after the last line of your code runs. And since those lines run later, the second console.log in your code tries to print userPosition.lat, but there’s nothing else in your code that sets that value, so you’ll see undefined.


#3

The issue is that getCurrentPosition() is an asynchronous request, meaning that code after the call could execute before the request returns with data. The only time you can guarantee a response will be received is inside your anonymous function, and that’s why the first console.log function will work and the second is not guaranteed to necessarily.


#4

Will using JASONP help?