javascript - Google Maps API - 仅限美国的自动完成预测

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

我正在使用名为“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);
}

有什么想法吗?谢谢。

最佳答案

您非常接近,但不幸的是,要获得此特定行为,您需要使用 getPlacePredictions() 而不是 getQueryPredictions()。这允许您使用 AutocompletionRequest但是有 componentRestrictions 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 作为选项对象的键

关于javascript - Google Maps API - 仅限美国的自动完成预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44972341/

相关文章:

javascript - 如果元素没有在 Angular JS 中显示,想要隐藏 "|"

javascript - 如何替换连接到另一个字符串的字符串?

javascript - 是否可以修改 Google Maps V3 中的缩放过渡?

ios - GMSAutocompleteViewController 仅显示 5 个结果

Android,无法解析方法 getMap()

android - 如何获取两站之间的所有巴士站名称?

api - "marker.getPosition is not a function"而 markerclustering

javascript - 无法导入html中的js文件

javascript - ES6 : Can i init variable with value of the result of destruction of an object?

google-maps - 在 map 上调用 fitBounds 函数时不要触发 'zoom_changed' 事件