0

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?

1
  • Which variable are you talking about and what do you mean by "it won't read it"? Commented Jan 22, 2011 at 21:06

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

it is being populated, but the maps dont show nethng, coz i believe that since the setCenter has already been executed, the maps api does not know what to show...
Amit -- that sounds like more of a Google Maps API question than "jquery callback not using global variable." The callback is indeed using the global variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.