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 =
My one-liner using a functional approach and map
, filter
, and ES2015:
/**
* Get the value for a given key in address_components
*
* @param {Array} components address_components returned from Google maps autocomplete
* @param type key for desired address component
* @returns {String} value, if found, for given type (key)
*/
function extractFromAddress(components, type) {
return components.filter((component) => component.types.indexOf(type) === 0).map((item) => item.long_name).pop() || null;
}
Usage:
const place = autocomplete.getPlace();
const address_components = place["address_components"] || [];
const postal_code = extractFromAddress(address_components, "postal_code");