【问题标题】:Exclude Certain Locations in Google Maps Autocomplete在 Google 地图自动填充功能中排除某些位置
【发布时间】:2019-04-29 19:17:39
【问题描述】:

您如何阻止某些国家/地区出现在 Google 地图自动填充功能中?

我找到了几种解决方案,可以将搜索范围缩小到某些区域,但我正在寻找一种方法来进行全局搜索,而只丢失几个位置。

背景:

我有一些国家对我来说是非法的,比如世界上 10~ 个。我们有一个带有谷歌地图自动填充功能的文本框,用于全球搜索,我不希望这些国家/地区显示为选项。

我找到了将自动完成功能限制在最多 5 个国家/地区 (componentRestrictions) 的方法,但我希望在下拉列表中启用 240~ 个国家/地区,并且不想看到这 10 个国家/地区。我发现与此解决方案相关的唯一其他答案围绕着将来自 .pac-containers 的自动完成结果与不同的限制 (240/5) 组合在一起,这将为每个角色产生大量调用。

我研究过的其他地图options,如boundscomponents,都围绕着将搜索范围限制在一个空间内,而不是从全局空间中排除某些位置。

代码设置:

API:

https://maps.googleapis.com/maps/api/js?key=${googlePlacesApiKey}&libraries=places

自动完成:

new google.maps.places.Autocomplete(input, options)

限制示例:

restrictions = { 'country': ['CU', 'AE', 'AF', 'AG', 'AI'] }
this.autocomplete.setComponentRestrictions(restrictions);
this.options.componentRestrictions = restrictions;

(对国家/地区的限制最多为 5 个 - 玩转限制,google hosts a nice js fiddle with documentation。)

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 autocomplete google-places-api


    【解决方案1】:

    这适用于包含方法(include数百个国家):就像 Chaussin 在 https://codepen.io/fchaussin/pen/KgEApw?editors=0010

    这会通过只呈现您想要的国家/地区来阻止某些国家/地区出现。

    本质上,将多个service.getPlacePredictions 循环在一起,然后找出显示它们的方法。这需要很长时间(您将收到大量超过查询限制的请求,因为 Google 限制了他们每分钟的 api),并且对于任何想要为数百个国家/地区提供扩展预测的生产级服务都远不实用,但适用于轻松超过 5 个。

    countries = [...long string of country codes]
    
      getAllPredictions(searchText) {
        const service = new google.maps.places.AutocompleteService();
        return Promise.all(
          _.chunk(this.countries, 5).map(countries => {
            return this.getPrediction(searchText, countries);
          })
        ).then(predictions => {
          return _.filter(_.flatten(predictions));
        });
      }
    
      getPrediction(searchText, country) {
        return new Promise( (resolve, reject) => {
          service.getPlacePredictions({
            input: searchText,
            componentRestrictions: {
              country: country,
            },
            types: ['(cities)']
          }, async (data, status) => {
            if( status === 'OVER_QUERY_LIMIT'){
              resolve( await this.getPrediction(searchText, country) );
            }else{
              resolve(data);
            }
          });
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2015-08-05
      • 1970-01-01
      • 2015-07-08
      • 2023-03-12
      • 2020-08-04
      • 2013-12-09
      相关资源
      最近更新 更多