0

I'm trying to locate the user's city and assign it to a global variable for further usage. I'm able to get the city by using geolocation and geocoder and alerting it out. My problem is.. how do I assign the return city to a global variable so i can use it outside the getCity function? Here's my code that will alert the user's current city location.

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
//get city fucntion
function getCity() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPos);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

//callback function to get lat and long
function showPos(position) {

    // lat and long
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;

    //new geocoder to reverse geocoding
    var geocoder = new google.maps.Geocoder();
    //set lat and long
    var latlng = new google.maps.LatLng(lat, lng);
    //get address
    geocoder.geocode({
        'location': latlng 
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                //get city
                alert(results[0]['address_components'][2].long_name);
            }
        }
    });//end geocoder callback

}//end showPos callback

getCity();

</script>

Code above will alert the user's city. Now I want the city to be assigned to a global variable so I can use it for something else. I've tried declaring a variable outside of the getCity() function and assigning it to results[0]['address_components'][2].long_name; like so...

var city;
function getCity() {
    city = results[0]['address_components'][2].long_name;
}
alert(city);

This doesn't do anything. Can someone give me some suggestions?

Stephen P
  • 14,422
  • 2
  • 43
  • 67
lys916
  • 307
  • 2
  • 5
  • 18
  • 1
    You need to consume the data in the callback since geocoder is asynchronous. Your alert will fire before the data is returned – charlietfl Jan 12 '16 at 01:29
  • Can give me an example? I don't know what you mean by consume the data. I've tried putting all my other codes that uses the 'city' result inside the the callback and it works. Is there a way that I can use the result outside the callback? – lys916 Jan 12 '16 at 01:59
  • No.. you can't use it until it has been returned – charlietfl Jan 12 '16 at 02:05
  • duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – geocodezip Jan 12 '16 at 02:08

1 Answers1

0

To be more explicit, you can use it outside the callback, but you have to wait for the callback to have been executed, so that your global variable is now assigned the correct value.

For example, see these situations:

var city;

function getCity() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPos);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
    alert(city); // shows "undefined" when called the first time
}

function showPos(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);

    geocoder.geocode({'location': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results[0]) {
            //get city
            city = results[0]['address_components'][2].long_name;
            alert(city); // shows the found city.
            showCity(); // shows the found city.
        }
    });
}

getCity();

function showCity() {
    alert(city);
}

showCity(); // shows "undefined" when called here.

Please read the post recommended by geocodezip in your question comments. Once you understand Asynchronous tasks in JavaScript, everything will make more sense.

ghybs
  • 47,565
  • 6
  • 74
  • 99