使用AutocompleteService将Google地图位置限制在特定国家/地区()

时间:2016-04-28 07:54:24

标签: javascript google-maps

使用google.maps.places.AutocompleteService如何限制搜索国家/地区(加拿大和美国)。如果您正在使用AutoComplete,则可以将国家/地区添加到选项中,但使用AutocompleteService似乎并非如此。我在查看文档componentRestrictions时也发现了,但这也不起作用。

如何使用Google商家信息限制搜索的国家/地区?

function initService(controlInput) {

  var service = new google.maps.places.AutocompleteService();

  var displaySuggestions = function(predictions, status) {

      if (status != google.maps.places.PlacesServiceStatus.OK) {
          console.log(status);
          return;
      }

      predictions.forEach(function(prediction) {
          console.log(prediction);
      });
  };

  controlInput.addEventListener('keyup', function(event, input) {
      service.getQueryPredictions({ 
        input: controlInput.value,
        //country: 'ca',  <--- doesn't work
        componentRestrictions: {
          country: 'ca' <--- also doesn't work
        }
      }, displaySuggestions);
  });
 }

3 个答案:

答案 0 :(得分:0)

请尝试从Component Filtering开始使用本指南:

  

在地理编码响应中,Google Maps Geocoding API可以返回仅限于特定区域的地址结果。使用组件过滤器指定限制。过滤器由一个由管道(|)分隔的组件:值对列表组成。仅返回与所有过滤器匹配的结果。过滤器值支持与其他地理编码请求相同的拼写校正和部分匹配方法。如果地理编码结果是组件过滤器的部分匹配,则它将在响应中包含partial_match字段。

     

可以过滤的组件包括:

     
      
  • 路由匹配路由的长或短名称。
  •   
  • locality与locality和sublocality类型匹配。
  •   
  • administrative_area匹配所有administrative_area级别。
  •   
  • postal_code匹配postal_code和postal_code_prefix。
  •   
  • 国家/地区匹配国家/地区名称或两个字母ISO 3166-1国家/地区代码。
  •   
     

注意 :每个地址组件只能在地址参数或组件过滤器中指定,但不能同时指定。这样做可能会导致ZERO_RESULTS

     

圣克鲁斯&#34;圣克鲁斯的地理编码&#34; components=country:ES将返回西班牙加那利群岛的Santa Cruz de Tenerife。请求:

https://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=country:ES&key=YOUR_API_KEY

此处Restrict the search to a specific country还介绍了如何实施限制搜索并遵循ISO 3166-1(双字母国家/地区代码)。我希望这会有所帮助。

答案 1 :(得分:0)

您正在使用不接受componentRestrictions选项的AutocompleteService.getQueryPredictions方法。它对AutocompleteService.getPlacePredictions方法有效。参见文档:

AutocompleteService: https://developers.google.com/maps/documentation/javascript/reference#AutocompleteService

AutocompletionRequest: https://developers.google.com/maps/documentation/javascript/reference#AutocompletionRequest

QueryAutocompletionRequest: https://developers.google.com/maps/documentation/javascript/reference#QueryAutocompletionRequest

答案 2 :(得分:0)

我使用了国家/地区选择选项来设置autocomplete.setComponentRestrictions的值。

自动填充功能仅限于从该国家/地区进行搜索。 请原谅格式,因为我刚把它放在这里。

    function setAutocompleteCountry() {
    var country = document.getElementById('id_countryselect').value;
    if (country === 'ALL') {
        autocomplete.setComponentRestrictions({'country': []});
    } else {
        autocomplete.setComponentRestrictions({'country': country});
    }
}

autocomplete.addListener('place_changed', function () {
        var place = autocomplete.getPlace();
    ------> Rest of code