GeocoderResult 返回一个对象数组(我见过数组元素的数量范围从南极洲的 1 到东京的 16)。数组中的每个对象都包含以下属性:
- address_components:包含多个描述地址的对象的数组。这些对象中的每一个都包含一个 long_name 属性(字符串)、short_name 属性(字符串)和 type 属性(数组,如下所述)
- formatted_address:描述地址的直观单个字符串
- 几何:处理经度/纬度/视点
- 类型:由 https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingAddressTypes 描述.
返回数组中的第一个对象似乎是最具描述性的物理地址(总是这样吗?),它包含的“formatted_address”似乎总是满足我的需求。问题是我不需要一根绳子,而是每个部分。
例如,典型的美国格式化地址可能如下:
- 美国密歇根州范布伦
- 244 号国道,农达普,MT 59072,美国
- 24 West 18th Avenue, 斯波坎, WA 99203, 美国
对于这三个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;
}
最佳答案
我建议使用address_components
。在 formatted_address
中,您不会知道哪个路径表示哪个管理级别。
关于javascript - 从 GeocoderResult 获取 formatted_address 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14172487/