我正在使用名为“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()
location
或 bounds
作为选项对象的键
关于javascript - Google Maps API - 仅限美国的自动完成预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44972341/