javascript - 使用 Google map 地理编码器以及国家/地区的地址和组件限制

标签 javascript jquery google-geocoder google-geocoding-api

我的表单上有一个字段正在使用 Google 自动完成功能

new window.google.maps.places.Autocomplete(location, { types: ['geocode'] });

但如果用户没有从自动完成中选择下拉菜单,我需要谷歌地图地理编码器在提交表单时进行搜索。我希望我的用户选择世界上任何地方的街道、城镇、城市、社区等!

var navbarGeocoder = new google.maps.Geocoder();
navbarGeocoder.geocode({
      'address': location.value
    }, function(results, status) {

但现在我希望能够使用国家/地区(美国)的组件限制将地理编码器限制为美国(街道、社区、城市、城镇等),但是当我在下面尝试此操作时,它只是挂起!

var navbarGeocoder = new google.maps.Geocoder();
navbarGeocoder.geocode({
  'address': location.value
}, {
  componentRestrictions: {
    country: ' US'
  }
}, function(results, status) {

  if (status === google.maps.GeocoderStatus.OK) {
    // do something
  } else {
    // do something
  }

});

是否有正确的方法来添加组件限制并仍然保留地址字段?任何帮助将不胜感激!

我正在使用这个link到 Google 网站获取文档,组件限制中是否有一个字段的作用类似于地址字段?

最佳答案

通过查看您提供的文档,我认为您的问题实际上可能非常简单 - 尽管我还没有亲自测试过。无论如何,如果您向上滚动到“地理编码请求”部分,您将看到以下代码。

{
 address: string,
 location: LatLng,
 placeId: string,
 bounds: LatLngBounds,
 componentRestrictions: GeocoderComponentRestrictions,
 region: string
}

所以,我认为您只需将 componentRestrictions 字段放在与实际地址相同的数组中即可。 如果有帮助请告诉我:)

因此,不要尝试您发布的内容,而是尝试这个...

var navbarGeocoder = new google.maps.Geocoder(); 
navbarGeocoder.geocode({ 
    'address': location.value, 
    componentRestrictions: { 
        country: ' US' 
    } 
}, 

关于javascript - 使用 Google map 地理编码器以及国家/地区的地址和组件限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54641838/

相关文章:

javascript - iPhone Web App 禁用缓存

javascript - SVG 仅在 safari 中悬停时调整大小

swift - 在 iOS swift 中将 LAT/Long 转换为位置地址

android - Genymotion - 从经度和纬度获取地址

JavaScript while 循环将每个数据一一传递到另一个函数中

javascript - 检测浏览器(可能的返回值)

javascript - MomentJs格式落后一天

php - jQuery - 发布和回复

jquery - 如何在一页上有 2 个固定标题?

javascript - Uncaught Error : google is not defined for Google Map API geocoder