【发布时间】:2014-08-21 13:26:41
【问题描述】:
https://stackoverflow.com/a/6798005/2068148
上述链接中的答案由 Michal 回答。
从 geocoder.geocode 得到 results 后,我不明白他为什么要检查 if(results[1]) ,他本可以检查 if(results)...
请帮助我理解这一点。
【问题讨论】:
https://stackoverflow.com/a/6798005/2068148
上述链接中的答案由 Michal 回答。
从 geocoder.geocode 得到 results 后,我不明白他为什么要检查 if(results[1]) ,他本可以检查 if(results)...
请帮助我理解这一点。
【问题讨论】:
根据谷歌开发者网站:
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
所以,我认为应该是results[0],更多详情请见Geocoding Strategies
请参阅下面的完整示例响应 formatted_address
{
"status": "OK",
"results": [ {
"types": street_address,
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": street_number
}, {
"long_name": "Amphitheatre Pkwy",
"short_name": "Amphitheatre Pkwy",
"types": route
}, {
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": [ "locality", "political" ]
}, {
"long_name": "San Jose",
"short_name": "San Jose",
"types": [ "administrative_area_level_3", "political" ]
}, {
"long_name": "Santa Clara",
"short_name": "Santa Clara",
"types": [ "administrative_area_level_2", "political" ]
}, {
"long_name": "California",
"short_name": "CA",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United States",
"short_name": "US",
"types": [ "country", "political" ]
}, {
"long_name": "94043",
"short_name": "94043",
"types": postal_code
} ],
"geometry": {
"location": {
"lat": 37.4220323,
"lng": -122.0845109
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 37.4188847,
"lng": -122.0876585
},
"northeast": {
"lat": 37.4251799,
"lng": -122.0813633
}
}
}
} ]
}
干杯!!
【讨论】:
你是对的。 if(results[1]) 似乎是一个错误/错字,因为 geocoder.geocode 将结果写入数组(如文档中的 here 所述)。
因此,results 数组的每个结果都有一个对象。这也可以通过在代码运行时检查console.log 消息来看到——Michal 的代码中有一个console.log(results)。
if 语句应该是:if(results.length > 0) 甚至是if(results[0]),但即使这样也是多余的,因为如果没有结果,前面的 if 语句:if (status == google.maps.GeocoderStatus.OK) 将解析为 false(status="ZERO_RESULTS ")。
因此您可以删除 if(results[1]) 或将其替换为 if(results.length > 0) 或 if(results[0])。
【讨论】: