PlacesAutocomplete 是 Google Maps JavaScript API 中的一个功能,用于实现地点搜索的自动补全。它通过用户输入的部分关键词,实时返回匹配的地点预测结果(如地址、POI等),提升搜索体验。核心类为 google.maps.places.Autocomplete
。
通过 Autocomplete
的 options
参数配置:
const autocomplete = new google.maps.places.Autocomplete(
document.getElementById("inputField"),
{
types: ["geocode"], // 可选类型:'establishment'(商家), '(cities)', '(regions)'等
bounds: new google.maps.LatLngBounds(
new google.maps.LatLng(swLat, swLng),
new google.maps.LatLng(neLat, neLng)
), // 限制搜索地理范围
componentRestrictions: { country: "us" }, // 限制国家
fields: ["name", "geometry"], // 返回的字段
}
);
places
库。place_changed
事件:place_changed
事件:<!DOCTYPE html>
<html>
<head>
<title>Places Autocomplete Demo</title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
</head>
<body>
<input id="address" placeholder="输入地址" type="text" />
<script>
const input = document.getElementById("address");
const autocomplete = new google.maps.places.Autocomplete(input, {
types: ["geocode"],
componentRestrictions: { country: "us" },
});
autocomplete.addListener("place_changed", () => {
const place = autocomplete.getPlace();
if (place.geometry) {
console.log("坐标:", place.geometry.location.lat(), place.geometry.location.lng());
} else {
console.log("无地理信息");
}
});
</script>
</body>
</html>
status
事件处理错误(如 ZERO_RESULTS
)。通过合理配置和事件处理,PlacesAutocomplete 能显著提升地理搜索功能的用户体验。
没有搜到相关的文章