Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient way to extract address components

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?

like image 265
0xbadf00d Avatar asked Nov 29 '11 16:11

0xbadf00d


2 Answers

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...

like image 151
Johann Avatar answered Nov 19 '22 04:11

Johann


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");
like image 17
user1429980 Avatar answered Nov 19 '22 06:11

user1429980