以下页面将您带到Google Maps API-放置自动完成地址表单,这是您可能使用的工作的一个工作示例。
放置自动完成地址表格
在他的页面中,您会看到代码示例,其中以下子例程:
// 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;
}
}
您可以看到,循环代码非常动态。
任何人都可以向我展示如何将每个地址字段分别返回他们自己的变量或数组,以便我可以以任何给定的顺序重新将其重建为字符串?
您可以使用对象JS
var your_obj = {};
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;
your_obj[addresType] = val;
}
}
//and after that you can use it where you uant like:
var postal_code = your_obj['postal_code'];
//check first console.log() to know all items in your_obj
console.log(your_obj);