I have a function in my map.js file called getNameOfCity() (The function is below) It is called from my actions.js file by doing the following var city = getNameOfCity(); I then alert city and it says undefined.
Here is the function in map.js
function getNameOfCity() {
geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]){
jQuery.each(results[0].address_components, function(key, value){
if(value.types[0] == 'locality') {
return value.long_name;
}
});
}
} else {
return false;
}
});
}
When I alert value.long_name just before I return the correct city is alerted. But when I alert city back from where the function was called it returns undefined. Any ideas on why?
Thanks
as Adam said, the problem is you are returning to the anonymous function. do this instead:
UPDATE
The callback way, as you were suggested…
UPDATE 2
You can now use this function to get the city name this way: