简体   繁体   中英

Can't change value of global variable JS

I have 2 global variables : Lon and Lat And I want to change the value of these variables inside the function of geolocalisation offered by HTML5: here is my code :

window.lat={{geo['latitude']}};
window.lon={{geo['longitude']}};
var SK= readCookie('SK');
if(SK==1)
{
    navigator.geolocation.getCurrentPosition(function(e){
    window.lat=e.coords.latitude;
    window.lon=e.coords.longitude;
    window.zoomi=15;
    })
}

the final value of window .lat is always

window.lat={{geo['latitude']}}

Does anyone know why ?

PS: the SK==1 is true, and inside the function(e), I tried to alert the values and they really change. but once out of the function, everything vanishes

Javascript is always synchronous and single-threaded so if you are checking window.lat after callback it gets executed even before gelocation call and it has same value.geolocation takes few seconds to get the value and you must write up your code in callback fucntion or write a function to use geolcoation values.

window.lat=1;
window.lon=3;
var SK= 1
if(SK==1)
{
    navigator.geolocation.getCurrentPosition(showPosition);

}


//anything written here will be executed before even the getCurrentPosition retuns or sets the results

function showPosition(position)
{
     alert("Latitude: " + position.coords.latitude +  "-Longitude: " + position.coords.longitude); 
    //write your code here to use the location 
} 

here is the jsfiddle http://jsfiddle.net/Xa64Q/ explaining the issue if we are running alert after few seconds it returns correct value

Step through it with a debugger (like Chrome dev tools or Firebug for Firefox). This code works and is the same in principle. It works just fine for this sort of variable assignment:

window.x = 1;
function change() {
 window.x = 2;   
}
change();
alert(window.x);

My guess is that the getCurrentPosition call is abruptly failing. BTW, that call takes an error call back handler so you should define one for your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM