https://stackoverflow.com/a/6798005/2068148
上述链接的答案由Michal回答。
从 geocoder.geocode 获取结果后,我不明白他为什么检查 if(results [1]) ,他本可以检查 if(results) ......
请帮助我理解这一点。
答案 0 :(得分:0)
根据Google开发者网站:
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
}
}
}
} ]
}
干杯!!
答案 1 :(得分:0)
你是对的。 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)
将解决为假(状态=" ZERO_RESULTS")。
因此,您只需移除if(results[1])
或将其替换为if(results.length > 0)
或if(results[0])
。