在Google Maps Autocomplete中排除某些位置

时间:2018-11-27 23:50:53

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

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

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

背景

我在某些国家(例如10个国家)非法经营我的产品。我们有一个带有Google地图自动完成功能的文本框,可进行全球搜索,但我永远不希望这些国家/地区显示为选项。

我已经找到了将自动完成功能限制为最多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进行限制。)

1 个答案:

答案 0 :(得分:0)

这适用于包含方法(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);
        }
      });
    });
  }
相关问题