简体   繁体   中英

jquery callback not using global variable

I have a small script that gets the location from geoplugin... i want to store the returned co-ords in a variable i have declared globally... but for some reason the callback wont read it. How do i make the callback use the global variable?

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    }, function() {
        noLocation();
    },{timeout: 20});
}
else if (google.gears) {
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.latitude,position.longitude);
    }, function() {
        noLocation();
    });
}
else {
    noLocation();
}
function noLocation() {
$.getJSON("http://www.geoplugin.net/json.gp?id=117.201.92.17&jsoncallback=?",
    function(data) {
        if (data != "" && data.geoplugin_latitude != "")
            myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
        else
            myLocation = new google.maps.LatLng()
    });

}

For some reason i think its because of the asynchronous call... Can i get over the issue some how?

It looks like it is storing it in the global variable "myLocation". However, it's likely that you are attempting to read the value before it has actually been set. The way an asynchronous call works is that it returns immediately, then sometime in the future, it will call the callback function if and when the request gets a response. The rest of your code will continue to run in the meantime.

Try an "alert" after the assignment to myLocation to see if it is being populated:

myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
alert(myLocation)

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