Ad

Using Geolocation And Geocoder To Locate The User's City And Assign It To A Variable

- 1 answer

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad