Luc
Luc

Reputation: 17082

node.js, cannot get returned result from inner function

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.

Upvotes: 1

Views: 438

Answers (1)

thejh
thejh

Reputation: 45578

geocoder.reverseGeocode is async, which means that you can't return the result from inside the callback. Try something like this:

function getCityFromCoordinates(lat, long, cb){
 return geocoder.reverseGeocode(lat,long, function ( err, data ) {
    var city = "-";
    if(err){
       return cb(err.message);
    } else {
       if(data["results"].length == 0){ 
          return cb("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);
    cb(null, city);
 }); 
}

Now you can use it like this in your code:

getCityFromCoordinates(lat, long, function(err, city) {
  if (err) {
    console.log('error: '+err);
  } else {
    console.log('result: '+city);
  }
});

Upvotes: 5

Related Questions