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?