This is the sample code from Github. I am trying to geocode a user-submitted address and extract more information from by creating a function geocodeAddress (see the second block).
// Geocode an address.
googleMapsClient.geocode({
address: '1600 Amphitheatre Parkway, Mountain View, CA'
}, function(err, response) {
if (!err) {
console.log(response.json.results);
}
});
When I console.log the object it works but returns undefined. I have tried to initialize my object globally without success.
exports.geocodeAddress = function (address) {
var newGeocodedAddress = {};
googleMapsClient.geocode({ address: address }, function(err, response) {
if (!err) {
newGeocodedAddress.lat_lng = [response.json.results[0].geometry.location.lat, response.json.results[0].geometry.location.lng];
newGeocodedAddress.formatted_address = response.json.results[0].formatted_address;
newGeocodedAddress.place_id = response.json.results[0].place_id;
var address_components = response.json.results[0].address_components;
for (var i = 0; i < address_components.length; i++){
if ('locality' === address_components[i].types[0]) {
newGeocodedAddress.city_name = address_components[i].long_name;
}
if ('administrative_area_level_1' === address_components[i].types[0]) {
newGeocodedAddress.province = address_components[i].short_name;
}
if ('country' === address_components[i].types[0]) {
newGeocodedAddress.country_code = address_components[i].short_name;
}
if ('postal_code' === address_components[i].types[0]){
newGeocodedAddress.postal_code = address_components[i].long_name;
}
}
}
// console.log(newGeocodedAddress) returns the expected value
return newGeocodedAddress; // returns undefined
});
};
strong text