I am using Node.js. I created a funtion called locationToAddress, but it always returns undefined. This is the code simplified:
var lat = '-34.491093';
var long = '-58.558597';
console.log(locationToAddress(lat, long));
function locationToAddress(lat, long) {
var preUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=';
var apiKey = '<API_KEY>';
var url = preUrl + lat + ',' + long + apiKey;
var addressString = '';
request(url, function (error, response, body) {
try {
var jsonLocationObject = JSON.parse(body);
addressString = JSON.stringify(jsonLocationObject.results[0].formatted_address);
addressString = addressString.replace(/["]/g, '');
console.log(addressString);
return addressString;
} catch (e) {
return 'Could not find address';
}
});
}
In the console, This code should be seen as:
<FORMATTED_ADDRESS>
<FORMATTED_ADDRESS>
But I see:
undefined
<FORMATTED_ADDRESS>
I know the error is in the return of the value as it works perfectly if I call the function without logging the return.