JS value of variable is not seen after if statement

JS value of variable is not seen after if statement
0

#1

Hi,

I have simple JS code to get geolocation, geolocation is working, but the value is not stored in the variable I declared before if. They are seen if access from if but not once if is closed.

Please give me advice what I am doing wrong, thx here is my code:
$(document).ready(function()
{
var myLatitude = “”;
var myLongitude = “”;

if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
//$("#data").html("latitude: " + position.coords.latitude + "
longitude: " + position.coords.longitude);
myLatitude = position.coords.latitude;
console.log("In if: " + myLatitude + " " + myLongitude);
myLongitude = position.coords.longitude;
});
}

console.log("After if: " + myLatitude + " " + myLongitude);
});


#2

What you are not understanding is the asynchronous nature of the the navigator.geolocation.getCurrentPosition function.

Your variables myLatitude and myLongitude are assigned blank strings in the global scope. When the above getCurrentPosition function is called, it only assigns the position values once it actually gets the data back. While it is waiting, the rest of the code after the getCurrentPosition function call goes ahead even if the data is not back yet. This is why you will notice the order of the console.log statements are not in the same order as you wrote them in your code.

The reason it displays After if: " is because the 2nd console.log executes before the data is back in time to be assigned to your myLatitude and myLongitude variables. Later (milliseconds that is), when the position data has successfully return, the variables are assigned their values and then 1st console.log displays "In if: 37.4021757 "


#3

Getting the location is an asynchronous operation. So the JS engine will carry out that operation when it can fit it in (i.e. at some point in time the device will return the location coordinates, JS will not pause the program until that happens) Console logging can happen immediately, so the JS engine will do that first while it waits. If you log inside the callback, you should get the location values.