0

I am working on node.js library called node-geocoder. I am trying to create a function which will return only country name. My code is given below:

const NodeGeocoder = require('node-geocoder');

var NodeGeocoderOptions = {
  provider: 'google',

  // Optional depending on the providers
  httpAdapter: 'https',
  apiKey: gmapkey,
  formatter: null         
};

var geocoder = NodeGeocoder(NodeGeocoderOptions);

// get country
function getCountry(lat, long){

    country_name = "";

    geocoder.reverse({lat:lat, lon:long}, function(err, res) {
      // country_name = res[0].country;
      country_name += res[0].country;
    });

    console.log("Country Name is " + country_name);
    return country_name;

}

I am getting the response.how can i return country name.

Thanks in advance.

  • where and how do you declare the variable? I don't see a variable decleration in your code. – Mark Baijens Mar 02 '18 at 10:05
  • You need to declare variables in Javascript before using them. `var country_name = "";` – connexo Mar 02 '18 at 10:06
  • your problem ain't the assignment to the variable, your problem is time. You assign the value AFTER the outer function has returned. Check out Promises – Thomas Mar 02 '18 at 10:06
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Thomas Mar 02 '18 at 10:07
  • In async programming you can't do that. The `function(err, res)` is a callback called in a non-predictable moment, in a separate execution flow. The `reverse()` function sends some kind of request and doesn't wait for the answer, the flow goes on to the `console.log()` immediately, so your `country_name` will always be empty. – Oneiros Mar 02 '18 at 10:08
  • `country_name = "";` will result in searching down the scope chain. Will seek that property down the chain. Do `var country_name = "";` – Learn on hard way Mar 02 '18 at 10:09

0 Answers0