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 = 0; i < results[0].address_components.length; ++i)
{
for (j = 0; j < results[0].address_components[i].types.length; ++j)
{
if (!country && results[0].address_components[i].types[j] == "country")
country = results[0].address_components[i].long_name;
else if (!postal_code && results[0].address_components[i].types[j] == "postal_code")
postal_code = results[0].address_components[i].long_name;
else if (!locality && results[0].address_components[i].types[j] == "locality")
locality = results[0].address_components[i].long_name;
else if (!sublocality && results[0].address_components[i].types[j] == "sublocality")
sublocality = results[0].address_components[i].long_name;
}
}
That's unsatisfactory. Is there any other way to achieve the same result?
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...
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With