我正在构建一个地方自动填充地址表格,就像在这里看到的演示https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
一样然而,在演示中,街道号码和街道名称被放入分隔的字段中。我想要做的是连接street_number: 'short_name'
和route: 'long_name'
这两个值并将它们放入一个新字段。
我试图找到代码中存储这些值的位置,我看到这个数组
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
administrative_area_level_2: 'long_name',
postal_code: 'short_name'
};
所以如果我做console.log(componentForm);
它会返回整个事情。所以我尝试console.log(componentForm[route]);
,但控制台说route is undefined
所以我的问题是,如何找到街道号码和街道名称的价值,然后将它们连接到表格中的新字段?
发布我的完整脚本代码,因为它略有修改(我删除了地理编码服务并仅限制建议到美国地址,并且还将州县添加为返回值之一)
// load google api
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'long_name',
administrative_area_level_2: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to US locations
var input = document.getElementById('autocomplete');
var options = {
componentRestrictions: {
country: 'us'
}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
// 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) {
$(".autoSearch").hide(1000);
$(".hiddenForm").show(1000);
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]];
document.getElementById(addressType).value = val;
}
}
}
答案 0 :(得分:1)
当您编写componentForm[route]
时,javascript将查找路由变量并使用其内容作为componentForm对象的属性名称,因此没有路由变量,因此javascript告诉您它未定义。
如果您想访问路线属性,请执行此操作componentForm["route"]
或此componentForm.route
,要创建此新字段,您应该添加如下所示的行:
componentForm.full_address = componentForm.route + " " + componentForm.street_number;