使用google放置api并无法确定为什么autocomplete会在调用时返回undefined来获取地点。 开发人员工具显示的是。 address_components是调用autocomplete.getPlace时应返回的内容 无法获取未定义或空引用的属性“address_components”
function initAutoCompleteDynamic() {
var slideID = 99;
var idx = 99 - slideID;
var propcount = 5;
for (var i = 0; i < propcount; i++) {
var propaddress = "prop1address" + i;
var autocomplete = autocomplete + i;
autocomplete = new google.maps.places.Autocomplete(
document.getElementById(propaddress)),
{ types: ['geocode'] };
autocomplete.addListener('place_changed', fillinAddressDynamic);
}
}
和fillinAddressDynamic
var place=autocomplete.getPlace():
for (var i = 0; i < place.address_components.length; i++) {
alert("i am in the loop");
var addressType = place.address_components[i].types[0];
var field = addressType;
var completeaddress1 = '';
var propaddress = 'prop1address' + i;
var strnum = 'streetnumber' + i;
CR(i);//calling component resolver.
if (componentFormProduction[addressType]) {
var val = place.address_components[i][componentFormProduction[addressType]];
document.getElementById(CR[addressType]).value = val;
if (field == "street_number") {
var streetnum = document.getElementById(strnum).value = val;
}
if (field == "route") {
if (streetnum) {
completeaddress1 = streetnum + ' ' + val;
}
else {
completeaddress1 = val;
}
document.getElementById('prop1address0').value = completeaddress1;
}
}
}
答案 0 :(得分:0)
如果用户(或您)点击Enter而不点击建议,就会发生这种情况。
通常,事件的顺序如下:
address_components
)和触发places_changed
事件places_changed
的处理程序将通过调用getPlace()
然而,它也可能是这样的:
Enter
而不点击一个places_changed
事件places_changed
调用getPlace()
的处理程序并获取一个几乎为空的Place对象,只有name
字段包含原始用户输入。由您决定如何处理原始用户输入,以下是一些示例:
此工具使用JavaScript地理编码服务搜索该输入: https://google-developers.appspot.com/maps/documentation/utils/geocoder/
此示例(地址表单)不执行任何操作: https://google-developers.appspot.com/maps/documentation/javascript/examples/places-autocomplete-addressform
这个(非常基本的)示例将显示一条错误消息,报告没有详细信息: https://google-developers.appspot.com/maps/documentation/javascript/examples/full/places-autocomplete