目前,我正在使用Google Maps API中的AutocompleteService
类。从documentation中,我正在使用bounds
来应用纽约市的边界。但是,我从新泽西州和宾夕法尼亚州得到了结果。
AutocompleteService类没有strictBounds
选项,这使得很难将结果限制为仅在范围之内。以下是我为纽约市提供的以下界限:
/**
* NYC Bound Parameters for Google Maps API
* @enum {object}
*/
OfficeMap.NYC_BOUNDS = {
'south': 40.4773991,
'west': -74.25908989999999,
'north': 40.9175771,
'east': -73.7002721
};
但是,由于纽约以外的建议表明:
如上图所示,显示了PA的建议。
/** @private {this._google.maps.places.Autocomplete}Autocomplete instance */
this._service = new this._google.maps.places.AutocompleteService();
// Attach handler for the autocomplete search box. This updates the map
// position and re-sorts locations around that position.
this._searchEl.addEventListener('keyup', event => {
if(event.target.value) {
this._service.getPlacePredictions({
input: event.target.value,
offset: 3,
types: ['geocode'],
componentRestrictions: {country: 'us'},
bounds: OfficeMap.NYC_BOUNDS
}, predictions => {
if(predictions) {
let results = predictions.map(e => [e['description']]);
this._inputAutocomplete._autocomplete.options = results;
const autocompleteSelf = this._inputAutocomplete._autocomplete;
this._inputAutocomplete._autocomplete.select = () => {
if (autocompleteSelf.highlightedIndex !== -1) {
autocompleteSelf.input.value = autocompleteSelf
.scoredOptions[autocompleteSelf.highlightedIndex]
.displayValue;
autocompleteSelf.removeDropdown();
let nameOfLocation = autocompleteSelf.input.value;
let googlePlaceObj = this.getGooglePlaceByName(nameOfLocation,
predictions);
this.displayPlacesOnMap(googlePlaceObj);
}
};
}
});
}
});
方法
getPlacePredictions
仅应给出NYC建议,因为传递的是NYC界限参数。从documentation没有办法限制它。
如何限制AutocompleteService
getPlacePredictions
仅返回边界内的对象? 最佳答案
尤其是由于AutocompleteService
是@private
,因此似乎应该改用Autocomplete
类,该类确实支持strictBounds
。