Google Maps API - 仅限美国的自动填充预测

nac*_*n f 11 javascript maps google-maps google-maps-api-3

我正在使用名为" 检索自动填充预测 "的Google Maps API示例.我无法弄清楚如何过滤它,所以它只返回美国的地方.我知道如何用其他例子做到这一点......

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

autocomplete = new google.maps.places.Autocomplete(input, options);
Run Code Online (Sandbox Code Playgroud)

但我似乎无法弄清楚如何将它应用到我的例子中.这是我的代码......

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);
}
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,但它没有用.

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);
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢.

Ale*_*fis 5

你是如此非常接近,但不幸的是,你需要使用这种特定的行为,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);
Run Code Online (Sandbox Code Playgroud)

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