有人经历过吗?
我可以使用 Google 地图 API 自动完成地址,并且在输入时显示格式化的地址,但在单击后格式发生了变化。
注意到诺斯科特没有显示。
抱歉,我不太擅长编码,刚开始学习,但我无法弄清楚。
这是我在沙箱中测试时的代码:
const componentForm = [
'location',
'locality',
'administrative_area_level_1',
'country',
'postal_code',
];
const getFormInputElement = (component) => document.getElementById(component + '-input');
const autocompleteInput = getFormInputElement('location');
const autocomplete = new google.maps.places.Autocomplete(autocompleteInput, {
fields: ["address_components", "geometry", "name"],
types: ["address"],
});
autocomplete.addListener('place_changed', function () {
const place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: \'' + place.name + '\'');
return;
}
fillInAddress(place);
});
function fillInAddress(place) { // optional parameter
const addressNameFormat = {
'street_number': 'short_name',
'route': 'long_name',
'locality': 'long_name',
'administrative_area_level_1': 'short_name',
'country': 'long_name',
'postal_code': 'short_name',
};
const getAddressComp = function (type) {
for (const component of place.address_components) {
if (component.types[0] === type) {
return component[addressNameFormat[type]];
}
}
return '';
};
getFormInputElement('location').value = getAddressComp('street_number') + ' '
+ getAddressComp('route');
for (const component of componentForm) {
// Location field is handled separately above as it has different logic.
if (component !== 'location') {
getFormInputElement(component).value = getAddressComp(component);
}
}
}
}