1 回答
TA贡献1865条经验 获得超7个赞
看一下加载 Google Maps JavaScript API 的脚本:
<script defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initMap">
请注意,它具有以下参数callback=initMap
。这意味着一旦 Google Maps JavaScript API 完全加载,它将调用名为 name 的函数initMap()
。
您的代码中不存在此函数。您还有另一个名称为 name 的函数initAutocomplete()
,因此您应该在回调参数中使用此函数名称:
callback=initAutocomplete
.
编辑:
此外,您没有正确关闭标签。加载 Maps JavaScript API 的脚本必须以</script>
标签结束,后面<script>
跟着定义函数的代码部分。查看可以解决您的问题的代码片段。
<div id="locationField">
<input
id="autocomplete"
placeholder="Enter your address"
onfocus="geolocate()"
type="text"
/>
</div>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places&callback=initAutocomplete">
</script>
<script>
let placeSearch;
let autocomplete;
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById("autocomplete"),
{ types: ["geocode"] }
);
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(["address_component"]);
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocomplete.addListener("place_changed", getAddress);
}
function getAddress() {
console.log(autocomplete.getPlace());
}
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
const circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy,
});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
添加回答
举报