Amit
Amit

Reputation: 3990

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?

Upvotes: 0

Views: 1171

Answers (1)

Zach
Zach

Reputation: 7930

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)

Upvotes: 2

Related Questions