Google Maps AutoComplete API - 未捕获的类型错误:无法读取未定义的属性“apply”
2021-05-26
2580
我尝试使用 getPlace() 函数获取 Google AutoComplete API,以便将结果对象提供给我的 JavaScript 代码。执行此操作后,我尝试访问结果对象,但收到错误:Uncaught TypeError:无法读取未定义的属性“apply”。
这是我的 JavaScript 控制台:
js?key=MY_API_KEY&libraries=places&callback=initMap:229 Uncaught TypeError: Cannot read property 'apply' of undefined
at Sf.Oj (js?key=MY_API_KEY&libraries=places&callback=initMap:229)
at Object._.M.trigger (js?key=MY_API_KEY&libraries=places&callback=initMap:225)
at Yf (js?key=MY_API_KEY&libraries=places&callback=initMap:103)
at Yf (js?key=MY_API_KEY&libraries=places&callback=initMap:103)
at E9._.N.set (js?key=MY_API_KEY&libraries=places&callback=initMap:231)
at E9.ni (js?key=MY_API_KEY&libraries=places&callback=initMap:110)
at b (places_impl.js:65)
at places_impl.js:47
at Mu.e [as j] (places_impl.js:28)
at Object.c [as _lphbgh] (common.js:108)
我根据文档在函数调用和回调函数之外声明了自动完成变量,但它一直出现此错误。这是我的 JavaScript 代码:
let placesautocomplete;
function initMap() {
console.log("Google Maps Initialized");
var input = document.getElementById('Referral_Address');
placesautocomplete = new google.maps.places.Autocomplete(input, {
componentRestrictions: { country: ["us", "ca"] },
fields: ["address_components", "geometry"],
types: ["address"],
});
placesautocomplete.addListener("place_changed", FillInAddress());
}
function FillInAddress() {
const place = placesautocomplete.getPlace();
if (place !== undefined) {
for (const component of place.address_components) {
const componentType = component.types[0];
switch (componentType) {
case "street_number": {
address1 = `${component.long_name} ${address1}`;
console.log(address1);
break;
}
case "route": {
address1 += component.short_name;
break;
}
case "postal_code": {
postcode = `${component.long_name}${postcode}`;
console.log(postcode);
break;
}
case "postal_code_suffix": {
postcode = `${postcode}-${component.long_name}`;
break;
}
case "locality":
document.querySelector("#locality").value = component.long_name;
console.log(component.long_name);
break;
case "administrative_area_level_1": {
document.querySelector("#state").value = component.short_name;
console.log(component.short_name);
break;
}
case "country":
document.querySelector("#country").value = component.long_name;
break;
}
}
}
}
我的目标是在自动完成后填写地址并将其显示给用户,但每次都会收到错误。我首先将其记录到控制台以验证它是否正常工作,然后在它工作后对其进行更改。
自动完成字段本身工作正常,并且可以毫无问题地进行相应填写,但此错误阻止我的代码从自动完成中获取结果并利用它们显示给用户。
任何见解都值得赞赏。谢谢。
2个回答
尝试将您的自动完成对象传递到 google.maps.event.addListener 函数中,并在那里声明您的地点结果。
google.maps.event.addListener(placesautocomplete, 'place_changed', function () {
var place = placesautocomplete.getPlace();
FillInAddress(place);
});
它可能会在请求时被清除内存。
Eric Conklin
2021-05-27
删除 FillInAddress 函数后的 ()
placesautocomplete.addListener("place_changed", FillInAddress);
Omar Arturo
2021-10-07