javascript - Google 自动完成 API 首先返回我所在州的地点,而不是最多 "expected"地点

标签 javascript jquery google-maps autocomplete google-places

我在输入地址时使用 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/

相关文章:

javascript - Node JS for 循环和数组推送

javascript - 数字升序排序 - sort()

jquery - 如何在具有相同功能的 div 和按钮中分配空白区域?

iphone - 是否可以从 iPhone 应用程序中关闭漫游?

javascript - 带有智能定位信息框的 Google map 混搭

android - 在 Google map 中标记 Recyclerview 数据

Javascript:将 Json 字符串推送到 Json 对象

javascript - 如果 Vue.js :class ='' takes a boolean?,如何根据字符串将类添加到右侧导航元素

jquery - Bootstrap 导航栏不会以适当的方式折叠

jquery - 使用 jQuery 计算 div 下面没有 id 的 span 标签的数量