我正在向谷歌地理编码器发送lon / lat并获取试图分解为变量的响应数据,响应如下:
这是我的代码:
getFormattedAddress(result) {
const arrResult = result.address_components;
let itemRoute = '';
let itemLocality = '';
let itemCountry = '';
let itemPc = '';
let itemSnumber = '';
for(let address_item in arrResult) {
if (address_item.types[0] == "route") {
console.log(i + ": route:" + address_item.long_name);
itemRoute = address_item.long_name;
}
if (address_item.types[0] == "locality") {
console.log("town:" + address_item.long_name);
itemLocality = address_item.long_name;
}
if (address_item.types[0] == "country") {
console.log("country:" + address_item.long_name);
itemCountry = address_item.long_name;
}
if (address_item.types[0] == "postal_code_prefix") {
console.log("pc:" + address_item.long_name);
itemPc = address_item.long_name;
}
if (address_item.types[0] == "street_number") {
console.log("street_number:" + address_item.long_name);
itemSnumber = address_item.long_name;
}
}
}
我得到的错误是: 未捕获(承诺)TypeError:无法读取未定义的属性“0”
我缺少什么?
更新,json outprint:
[
{
"long_name": "29-31",
"short_name": "29-31",
"types": [
"street_number"
]
},
{
"long_name": "Götgatan",
"short_name": "Götgatan",
"types": [
"route"
]
},
{
"long_name": "Södermalm",
"short_name": "Södermalm",
"types": [
"political",
"sublocality",
"sublocality_level_1"
]
},
{
"long_name": "Stockholm",
"short_name": "Stockholm",
"types": [
"locality",
"political"
]
},
{
"long_name": "Stockholm",
"short_name": "Stockholm",
"types": [
"postal_town"
]
},
{
"long_name": "Stockholms län",
"short_name": "Stockholms län",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "Sverige",
"short_name": "SE",
"types": [
"country",
"political"
]
},
{
"long_name": "118 26",
"short_name": "118 26",
"types": [
"postal_code"
]
}
]
答案 0 :(得分:1)
var arr = [
{
"long_name": "29-31", "short_name": "29-31",
"types": [ "street_number" ]
},
{
"long_name": "Götgatan", "short_name": "Götgatan",
"types": [ "route" ]
},
{
"long_name": "Södermalm", "short_name": "Södermalm",
"types": [ "political", "sublocality", "sublocality_level_1" ]
},
{
"long_name": "Stockholm", "short_name": "Stockholm",
"types": [ "locality", "political" ]
},
{
"long_name": "Stockholm", "short_name": "Stockholm",
"types": [ "postal_town" ]
},
{
"long_name": "Stockholms län", "short_name": "Stockholms län",
"types": [ "administrative_area_level_1", "political" ]
},
{
"long_name": "Sverige", "short_name": "SE",
"types": [ "country", "political" ]
},
{
"long_name": "118 26", "short_name": "118 26",
"types": [ "postal_code" ]
}
]
for (var i=0; i< arr.length ; i++) {
if (arr[i].types.indexOf('route') > -1)
console.log( 'route ' + arr[i].long_name );
if (arr[i].types.indexOf('locality') > -1)
console.log( 'locality ' + arr[i].long_name );
}