大家!
我正在 Angular 应用程序 /angular v - 13/ 中使用 angular-google-maps /@angular/google-maps": "13.3.9"/ ,一切都很好,直到我遇到以下问题(希望有一些适当的解决方案)解决方案)。我在组件的 html 中有一个输入字段,用户在其中输入并选择一个位置,其中自动完成下拉列表建议正确的选项,因为我在 .ts 文件中使用:
this.autocomplete = new google.maps.places.Autocomplete(this.inputElement, { componentRestrictions: { country: 'US' } });
。
太棒了,我只列出了美国的地方,但现在我只想显示,比如说,州,甚至更好,只显示我想要的城市。 (我的意思是我有一个城市列表,每个城市都有其州),我希望用户能够仅在自动完成输入中选择位置。 从我读过的所有具有类似问题的文档和示例中,到目前为止我什么也没发现。 有人已经遇到过这个问题并找到了解决方案吗? 我想监听这个“place_changed”事件,并在触发时以某种方式自定义过滤值,但我不清楚如何完成它。
如果您能提供帮助,那就太好了! :)
您可以监听
place_changed
事件,然后手动过滤结果以仅包含您想要显示的地点。
在创建
Autocomplete
的组件中,为 place_changed
事件 添加事件侦听器
this.autocomplete = new google.maps.places.Autocomplete(this.inputElement, {
componentRestrictions: { country: 'US' }
});
this.autocomplete.addListener('place_changed', () => {
this.onPlaceChanged();
});
定义可以过滤结果的
onPlaceChanged
方法
onPlaceChanged() {
const place = this.autocomplete.getPlace();
// Check if the selected place meets your criteria (e.g., city and state)
if (this.isValidPlace(place)) {
// Handle the valid place
console.log('Selected Place:', place);
} else {
// Reset the input or display an error message
console.log('Invalid Place:', place);
}
}
isValidPlace(place: google.maps.places.PlaceResult): boolean {
// Implement your logic to determine if the place is valid (e.g., city and state check)
// Return true if the place is valid, false otherwise
}
在
isValidPlace
方法中,您可以实现自定义逻辑来检查所选地点是否符合您的条件。例如,您可以检查该地点是否在您的城市和州列表中
isValidPlace(place: google.maps.places.PlaceResult): boolean {
const validCities = ['City1', 'City2', 'City3']; // List of valid cities
const validStates = ['State1', 'State2', 'State3']; // List of valid states
const cityName = place.address_components.find(component =>
component.types.includes('locality')
)?.long_name;
const stateName = place.address_components.find(component =>
component.types.includes('administrative_area_level_1')
)?.long_name;
return validCities.includes(cityName) && validStates.includes(stateName);
}
您需要对其进行调整以匹配您的特定用例,并将占位符城市和州名称替换为有效城市和州的实际列表。