我正在尝试使用Google地方信息自动填充功能以两种形式填充地址字段。左侧的表单来自位置,右侧的表单用于目的地。 到目前为止,这就是我所掌握的内容,我不明白如何使此代码对两种形式都适用。同样,两种形式在同一页上并排放置。
var placeSearch, autocompleteFrom, autocompleteTo;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
postal_code: 'short_name'
};
var componentFormTwo = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
postal_code: 'short_name'
};
function initAutocomplete() {
autocompleteFrom = new google.maps.places.Autocomplete((document.getElementById('autocompleteone')),
{
types: ['geocode']
});
autocompleteTo = new google.maps.places.Autocomplete((document.getElementById('autocompletetwo')),
{
types: ['geocode']
});
autocompleteFrom.addListener('place_changed', fillInFromAddress);
autocompleteTo.addListener('place_changed', fillInToAddress);
}
function fillInFromAddress() {
var place = autocompleteFrom.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
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;
}
}
}
function fillInToAddress() {
var placetwo = autocompleteTo.getPlace();
for (var component in componentFormTwo) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
for (var i = 0; i < placetwo.address_components.length; i++) {
var addressType = placetwo.address_components[i].types[0];
if (componentFormTwo[addressType]) {
var val = placetwo.address_components[i][componentFormTwo[addressType]];
document.getElementById(addressType).value = val;
}
}
}