以下页面将您带到Google Maps API - 放置自动填充地址表单,这是您可以使用它的一个工作示例。
Place Autocomplete Address Form
在他的页面中,您可以看到代码示例,其中包含以下子例程:
// 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;
}
}
正如您所看到的,这个For循环代码非常动态..
有人能告诉我如何将每个地址字段分别返回到自己的变量或数组中,以便我可以按照我选择的任何给定顺序将其重建为字符串吗?
答案 0 :(得分:0)
您可以使用对象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);