【问题标题】:Google Maps API - Autocomplete Predictions for USA onlyGoogle Maps API - 仅适用于美国的自动完成预测
【发布时间】:2017-07-07 13:42:54
【问题描述】:

我正在使用名为“Retrieving Autocomplete Predictions”的 Google Maps API 示例。而且我不知道如何过滤它,所以它只返回美国的地方。我知道如何使用其他示例来做到这一点......

var input = document.getElementById('searchTextField');
var options = {
      types: ['(cities)'],
      componentRestrictions: {country: 'us'}
    };

autocomplete = new google.maps.places.Autocomplete(input, options);

但我似乎不知道如何将它应用到我的示例中。这是我的代码...

function GetAddressPredictions(Search) {
    var displaySuggestions = function (predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
        return;
    }
    predictions.forEach(function (prediction) {
        PredictionArray.push(prediction);
    });
};
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({input: Search}, displaySuggestions);
}

我试过了,但是没用。

function GetAddressPredictions(Search) {
    var displaySuggestions = function (predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
        return;
    }
    predictions.forEach(function (prediction) {
        PredictionArray.push(prediction);
    });
};
var options = {
    types: ['(cities)'],
    componentRestrictions: {country: 'us'}
      };
    var service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions({input: Search, options}, displaySuggestions);
}

有什么想法吗?谢谢。

【问题讨论】:

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


    【解决方案1】:

    您非常接近,但不幸的是,要获得此特定行为,您需要使用 getPlacePredictions() 而不是 getQueryPredictions()。这使您可以使用具有componentRestrictionsAutocompletionRequest,但是QueryAutocompletionRequest 不支持componetRestictions,您必须退回到使用bounds 将搜索范围限制为一个框或使用location 来偏向搜索更喜欢某个点附近的位置。

    这是getPlacePredictions()的解决方案:

      var service = new google.maps.places.AutocompleteService();
      var options = {
        input: Search,
        types: ['(cities)'],
        componentRestrictions: {country: 'us'}
      };
      service.getPlacePredictions(options , displaySuggestions);
    

    如果您必须使用 getQueryPredictions() 执行此操作,您可以添加 locationbounds 作为选项对象的键

    【讨论】:

    • 完美运行。谢谢。
    【解决方案2】:

    函数getQueryPredictionsQueryAutocompletionRequest 对象作为其参数,而QueryAutocompletionRequest 没有将其限制为特定国家/地区的属性。

    也就是说,您可以在发送前简单地将“美国”或“美国”附加到查询中:

    service.getQueryPredictions({
       input: 'pizza near Syd' + ' usa'
    }, displaySuggestions);
    

    如果您不想在返回的结果中显示“, USA”,可以使用 JavaScript 的替换功能将其删除:

    predictions.forEach(function(prediction) {
       var li = document.createElement('li');
       li.appendChild(document.createTextNode(prediction.description.replace(', USA', '')));
       document.getElementById('results').appendChild(li);
    });
    

    演示:https://jsfiddle.net/sdz4yssL/2/

    还请注意,如果搜索词可能已经包含 USA 或其变体,那么您需要先从搜索词中删除所有出现的内容(通常使用正则表达式来忽略大小写敏感),否则搜索某些内容像“pizza usa usa”这样不会返回任何结果:

    input: (' ' + 'pizza near us Syd usa United States US' + ' ').replace(/ usa /ig,' ').replace(/ US /ig,' ').replace(/ united states /ig,' ') + ' usa'
    

    (我在查询之前和之后添加了一个空格,以便替换函数在开头和结尾处仍然匹配)

    【讨论】:

    • 我之前有过这个想法,但问题是,在您输入的开头,它的返回结果中包含字母 US.... 请参见此处的示例...s23.postimg.org/idefab67v/… - 这确实限制了它的能力。还有其他解决方案吗?
    • 我的正则表达式匹配 [space]US[space],所以没有尾随空格的 US-41 应该不是问题。你用我的代码试过了吗?
    • 如果您在屏幕截图中的查询中附加“US”,最好像我一样使用“USA”,甚至是“United States”
    • 等等,我如何删除像 US-41 这样的列表?你的代码的哪一部分是这样做的?
    • 如果您检查我的 jsfiddle 我将“美国”添加到搜索中,然后我将其从搜索结果中的显示中删除,这就是您的意思吗?在您的屏幕截图中使用 US-41 等,您要求谷歌在整个美国搜索一个数字;没有其他背景。如果我是 Google 搜索,我将不知道您在寻找什么。您希望返回什么?
    【解决方案3】:

    通过一些搜索,可以找到解决方案。

    该请求已于今年早些时候获得批准并发布:Google Request

    此类信息的文档可以从这里阅读:Google Documentation

    实施:

    HTML:

    <div id="text">
      Search Place:
    </div>
    
    <div id="locationField">
      <input id="autocomplete" placeholder="Enter text" type="text" />
    </div>
    
    
    <div id="map"></div>
    

    使用全局变量限制哪个国家/地区,UK 代表英国,US 代表美洲等...

    var countryRestrict = {
      'country': 'uk'
    };
    var autocomplete;
    

    然后使用以下内容构造自动完成:

     autocomplete = new google.maps.places.Autocomplete(
         (
          document.getElementById('autocomplete')), {
          componentRestrictions: countryRestrict
        });
      places = new google.maps.places.PlacesService(map);
    
      autocomplete.addListener('place_changed', onPlaceChanged);
    

    当文本发生变化时,我们调用 onPlacesChanged 函数:

    function onPlaceChanged() {
      var place = autocomplete.getPlace();
      if (place.geometry) {
        map.panTo(place.geometry.location);
        map.setZoom(5);
        var marker = new google.maps.Marker({
          position: place.geometry.location,
          map: map,
        });
      } else {
        document.getElementById('autocomplete').placeholder = 'Enter a Value';
      }
    }
    

    这会调用 get place 函数并为您点击的值添加一个标记。

    JSFIDDLE:https://jsfiddle.net/hn8091fk/

    【讨论】:

      【解决方案4】:

      你有没有尝试过这样的事情:

      function GetAddressPredictions(Search) {
      
          var displaySuggestions = function(predictions, status) {
              if (status != google.maps.places.PlacesServiceStatus.OK) {
                  return;
              }
      
              predictions.forEach(function(prediction) {
                  PredictionArray.push(prediction);
              });
          };
      
          var service = new google.maps.places.AutocompleteService();
          service.getQueryPredictions({ 
                  input: Search, 
                  types: ['(cities)'], 
                  componentRestrictions: {country: 'us'} 
              }, displaySuggestions);
      }
      

      【讨论】:

      • 对不起。没用。它仍在返回其他国家/地区的结果。控制台没有错误,所以我能给你的东西很少。
      【解决方案5】:

      与上述相反,AutocompleteService 采用QueryAutocompletionRequestAutocompletionRequest,所以我认为您传递选项的方式是错误的。是不是很简单:

      var options = {
          input: Search, 
          types: ['(cities)'],
          componentRestrictions: {country: 'us'}
      };
      
      var service = new google.maps.places.AutocompleteService();
      service.getQueryPredictions(options, displaySuggestions);
      

      还请记住,这完全是为了预测偏差,您不能要求 PAC 排除结果,只能排除偏差。

      【讨论】:

      • 我按照你说的做了,但是没有用。第一个结果是在西班牙。我发现结果与我的原始代码没有区别。无论如何感谢您的尝试。
      • @nachshonf 对此感到抱歉。有没有机会创建一个 jsfiddle 或类似的东西来看看它?我之前没有通过这些方法使用过 Google PAC
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 2011-02-25
      • 2015-10-07
      • 2023-03-12
      • 1970-01-01
      • 2012-08-09
      相关资源
      最近更新 更多