I have done this function, using geocoder module, to get the city from a couple of lat/long:
// Get city from lat/long pair
function getCityFromCoordinates(lat, long){
return geocoder.reverseGeocode(lat,long, function ( err, data ) {
var city = "-";
if(err){
city = err.message;
} else {
if(data["results"].length == 0){
city = "not found";
} else {
city = "";
var first_item = data["results"][0];
var address_components = first_item["address_components"];
for (var i=0; i<address_components.length;i++){
var current = address_components[i];
var types = current["types"];
for (var j=0;j<types.length;j++){
var type = types[j];
if((type == "locality") && (city == "")){
city = current["long_name"];
}
}
}
}
}
console.log("City:" + city);
return city;
});
}
When I call this function from another place, it correctly retrieve the city (I see this in the log) but it does not return the value. I’m sure this is linked to the geocoder.reserverGeocode function being embedded withing my function but I do not manage to fix this.
geocoder.reverseGeocodeis async, which means that you can’treturnthe result from inside the callback. Try something like this:Now you can use it like this in your code: