通过将地址组件提取到单独的表单字段中,此代码可以正常工作,但我的问题是它迫使我将 HTML 输入 ID 命名为与地址组件相同。例如,使用下面的 .js 代码,我需要:
<html>
<input id="postal_code"> and
<input id="locality">
</html>
如何更改 .js 语法,以便它仍然检索“postal_code”和“locality”组件,但将它们放入我命名的表单字段中:
<html>
<input id="zip_code"></input> and
<input id="city"></input>
</html>
这是(完整的)javascript;我原来的帖子只有一个片段:
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
postal_code: 'long_name',
locality: 'long_name',
country: 'short_name',
};
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(40.790908, -79.766323),
new google.maps.LatLng(-28.246058, 22.318632));
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('typeaddress')),
{bounds: defaultBounds,
types: ['address']});
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]];
document.getElementById(addressType).value = val;
}
}
}