我在输入地址时使用 Google 自动完成功能,这是简单的实现:
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('origin_address'), {types: ["geocode"]}
);
当我开始输入“Lon”时,第一个建议的地点是加利福尼亚州长滩
,下一个是“英国伦敦” - 这只是一个示例。
我位于加利福尼亚州。一般来说,当我开始输入地址时,提供给我的地点位于加利福尼亚州。我如何获得整个北美的名额?
我尝试修改我的自动完成设置,例如:
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('origin_address'), {types: ["route", "geocode"]}
);
但在这种情况下,自动完成功能没有提供任何内容(即使我仅将 route
保留在数组中。
如何设置自动完成功能以建议主要不是来自加利福尼亚州而是来自北美的地点?
最佳答案
试试这个:
navigator.geolocation.getCurrentPosition(position=> {
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ position.coords.latitude + "," + position.coords.longitude
+ "&sensor=false").then(data=> {
for (let component of data.results[0].address_components) {
if (component.types.includes("country")) {
new google.maps.places.Autocomplete(
$('#origin_address')[0], {types: ["geocode"],
componentRestrictions: {country: component.short_name}}
);
break;
}
}
})
})
首先,它使用浏览器的地理定位 API 获取当前位置。然后它向 Google Maps API 发出请求,根据纬度和经度获取国家/地区。然后它初始化自动完成功能,将其限制为该国家/地区。
参见JS Fiddle demo .
关于javascript - Google 自动完成 API 首先返回我所在州的地点,而不是最多 "expected"地点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36580430/