Currenty, I\'m using the following code to get the country, postal code, locality and sub-locality:
var country, postal_code, locality, sublocality;
for (i =
Visitors using underscore.js can easily convert the address_components
array in the geocode response into an object literal:
var obj = _.object(
_.map(results[0].address_components, function(c){
return [c.types[0], c.short_name]
})
);
You could use the following function to extract any address component:
function extractFromAdress(components, type){
for (var i=0; i<components.length; i++)
for (var j=0; j<components[i].types.length; j++)
if (components[i].types[j]==type) return components[i].long_name;
return "";
}
To extract the info you call:
var postCode = extractFromAdress(results[0].address_components, "postal_code");
var street = extractFromAdress(results[0].address_components, "route");
var town = extractFromAdress(results[0].address_components, "locality");
var country = extractFromAdress(results[0].address_components, "country");
etc...
Using lodash
const result = _.chain(json.results[0].address_components)
.keyBy('types[0]')
.mapValues('short_name')
.value()