gpt4 book ai didi

javascript - 如何为 HTML 输入 ID 命名不同于 Google Places API 的 address_component 的名称?

转载 作者:行者123 更新时间:2023-12-03 00:36:26 25 4
gpt4 key购买 nike

通过将地址组件提取到单独的表单字段中,此代码可以正常工作,但我的问题是它迫使我将 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;
}
}
}

最佳答案

您需要一个将表单 ID 映射到地址组件值的数据结构。这可以是任何东西,但这里有一个例子。

var componentForm = {
locality: {
formId: 'city',
addressComponentKey: 'long_name'
},
postal_code: {
formId: 'zip_code',
addressComponentKey: 'short_name'
}
}

function fillInAddress() {
// Get the place details from the autocomplete object.
var place = getPlace();
for (var component of componentForm) {
document.getElementById(component.formId).value = '';
document.getElementById(component.formId).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].addressComponentKey];
document.getElementById(componentForm[addressType].formId).value = val;
}
}
}

https://stackblitz.com/edit/google-places-form

关于javascript - 如何为 HTML 输入 ID 命名不同于 Google Places API 的 address_component 的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com