GeocoderResult返回一个对象数组(我已经看到数组元素的数量范围从南极洲的1到东京的16)。数组中的每个对象都包含以下属性:
返回数组中的第一个对象似乎是最具描述性的物理地址(总是这样吗?),其中包含的“formatted_address”似乎总能满足我的需求。问题是我不想要一个字符串而是每个部分。
例如,典型的USA formatted_address可能如下:
对于这三个formatted_addresses,我想得到以下内容:
{address:null, street: null, city:"Van Buren", state:"MI", zipcode: null, country:"USA"}
{address:null, street: "State Highway 244", city:"Roundup", state:"MT", zipcode: 59072, country:"USA"}
{address:24, street: "West 18th Avenue", city:"Spokane", state:"WA ", zipcode: 99203, country:"USA"}
我应该尝试解析formatted_address吗?或者我应该使用address_components,并以某种方式尝试提取我需要的部分?第二种解决方案似乎最好,可能看起来如下,但处理类型数组和短/长名称会使其变得困难。
如果我调用getAddressParts(GeocoderResult [0] .address_components),以下工作正常。
function getProp(a,type,lng) {
var j,rs;
loop:
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < a[i].types.length; j++) {
if(a[i].types[j]==type) {
rs=a[i][lng]
break loop;
}
}
}
return rs;
}
function getAddressParts(a) {
var o={};
o.street_number=getProp(a,'street_number','long_name');
o.route=getProp(a,'route','long_name'); //Street
o.establishment=getProp(a,'establishment','long_name'); //Used for parks and the like
o.locality=getProp(a,'locality','long_name'); //City
if(!o.locality){o.locality=getProp(a,'sublocality','long_name');} //Some city not available, use this one (needed for in lake michigan)?
if(!o.locality){o.locality=getProp(a,'administrative_area_level_2','long_name');} //Some city not available, use this one (needed for in lake michigan)?
o.administrative_area_level_1=getProp(a,'administrative_area_level_1','short_name'); //State
o.country=getProp(a,'country','short_name')+'A'; //A is for usA, and is just being used for testing
o.postal_code=getProp(a,'postal_code','long_name');
return o;
}
答案 0 :(得分:0)
我建议使用address_components
。在formatted_address
中,您不知道哪条路径表示哪个管理级别。