Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...