我遇到了一个问题。我正在使用 google maps api 地址自动填充。当我运行谷歌提供的示例代码时,它工作正常。但是当我在我的应用程序中使用它时,它适用于小输入,比如有小国家、城市名称的小输入。但是当我将它用于长时间输入时,它在控制台上给出了这个错误。
new:1381 Uncaught TypeError: Cannot read property 'length' of undefined
当我点击链接时,它会将我带到这段代码。
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
var valShort =place.address_components[i].short_name;
document.getElementById(addressType).value = val;
}
}
代码如下:
<script>
var placeSearch, autocomplete;
var componentForm = {
locality: 'long_name',
administrative_area_level_1: 'long_name',
country: 'long_name',
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
var valShort =place.address_components[i].short_name;
document.getElementById(addressType).value = val;
}
}
}
</script>
最佳答案
需要检查address_components是否存在。
根据 Autocomplete class引用:
If the user enters the name of a Place that was not suggested by the control and presses the Enter key, or if a Place detail request fails, a place_changed event will be fired that contains the user input in the name property, with no other properties defined.
所以你需要处理事件被触发但你返回的地方只有一个名字的情况。解决这个问题的一种方法是返回发送 Geocoding或 Place Text Search要求。对地址进行地理编码就足够了,但如果您还想查找商家,则需要地点文本搜索。
关于javascript - 谷歌地图地址自动填充错误 : Cannot read property 'length' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151036/