我正在尝试限制从 Google Maps geocoder API 返回的地址,如下所示:
var geocoder = new google.maps.Geocoder();
var auVicSwLatLon = new google.maps.LatLng(-39.234713, 140.962526);
var auVicNeLatLon = new google.maps.LatLng(-33.981125, 149.975296);
var auVicLatLonBounds = new google.maps.LatLngBounds(auVicSwLatLon, auVicNeLatLon);
geocoder.geocode(
{
address: searchStr,
region: 'AU',
// bounds: auVicLatLonBounds,
},
function(results, status) {
// ... do stuff here
}
);
使用区域的限制有效。然而,使用边界的限制没有——当我取消注释上面的边界属性时,我没有得到任何结果。留下评论,我得到了来自澳大利亚各地的结果。
是不是我做错了什么?
谢谢!
附加信息:
相关文档在这里:
https://developers.google.com/maps/documentation/javascript/geocoding
这里:
https://developers.google.com/maps/documentation/javascript/reference#Geocoder
请注意,我在 LatLngBounds
中使用的值适用于维多利亚州 (VIC)。这确实是我想要在这里实现的目标。因此,如果您知道实现此目的的替代方法,也请回答这个问题!
最佳答案
为什么不手动寻找满足边界要求的结果呢?
我遍历结果并使用 lat 和 lng 值检查其中第一个在限制区域内的结果。您还可以获得落入其中的所有结果。
function searchFromAddress() {
var address = document.getElementById("txtBxAddress").value;
// Check if input is not empty
if (address.length < 1) {
return;
}
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point;
// Find first location inside restricted area
for (var i = 0 ; i < results.length ; i++) {
point = results[i].geometry.location;
// I compare my lng values this way because their are negative
if (point.lat() > latMin && point.lat() < latMax && point.lng() < lngMin && point.lng() > lngMax) {
map.setCenter(point);
var marker = new google.maps.Marker({
position: point,
map: map,
title: "You are here",
icon: home_pin
});
break;
}
// No results inside our area
if (i == (results.length - 1)) {
alert("Try again");
}
}
}
});
}
关于javascript - Google Maps API 地理编码器,受边界限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11847638/