更有效的提取地址成分的方法 [英] More efficient way to extract address components

查看:30
本文介绍了更有效的提取地址成分的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在使用以下代码获取国家/地区、邮政编码、地区和子地区:

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?

推荐答案

if (typeof Object.keys == 'function')
    var length = function(x) { return Object.keys(x).length; };
else
    var length = function() {};

var location = {};      
for (i = 0; i < results[0].address_components.length; ++i)
{
    var component = results[0].address_components[i];
    if (!location.country && component.types.indexOf("country") > -1)
        location.country = component.long_name;
    else if (!location.postal_code && component.types.indexOf("postal_code") > -1)
        location.postal_code = component.long_name;
    else if (location.locality && component.types.indexOf("locality") > -1)
        location.locality = component.long_name;
    else if (location.sublocality && component.types.indexOf("sublocality") > -1)
        location.sublocality = component.long_name;

    // nothing will happen here if `Object.keys` isn't supported!
    if (length(location) == 4)
        break;
}

这是最适合我的解决方案.它也可以帮助某人.

This is the most suitable solution for me. It may help someone too.

这篇关于更有效的提取地址成分的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆