gpt4 book ai didi

javascript - 提取地址组件的更有效方法

转载 作者:数据小太阳 更新时间:2023-10-29 04:21:57 25 4
gpt4 key购买 nike

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

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;
}
}

这是不令人满意的。有没有其他方法可以达到同样的效果?

最佳答案

您可以使用以下函数来提取任何地址部分:

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 "";
}

要提取您调用的信息:

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");

等...

关于javascript - 提取地址组件的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8313876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com