我的网站上有2个输入字段,一个用于客户的完整地址,另一个用于邮政编码。由于数据库的原因,我需要将其作为2个不同的输入字段。 我想在我的网站上自动完成。我已经能够使用Google Places API。但是我希望它在一个输入字段中自动完成地址,并在另一字段中自动完成邮政编码。
如何做到?
这是我的代码当前代码。
$(document).ready(function() {
var autocompleteFrom;
autocompleteFrom = new google.maps.places.Autocomplete((document.getElementById('fromInput')), {
types: ['address'],
componentRestrictions: {
country: 'dk'
}
});
答案 0 :(得分:0)
相关问题:
Google Maps Javascript API v3文档中有一个相关示例,可以对其进行修改以仅从“自动完成”响应中获取邮政编码:Place Autocomplete Address Form
将component_form
对象更改为仅包含postal_code
:
var componentForm = {
postal_code: 'short_name'
};
然后在fillInAddress
事件触发时调用place_changed
函数:
autocompleteFrom.addListener('place_changed', fillInAddress);
代码段:
$(document).ready(function() {
var autocompleteFrom;
var placeSearch;
var componentForm = {
postal_code: 'short_name'
};
autocompleteFrom = new google.maps.places.Autocomplete((document.getElementById('fromInput')), {
types: ['address'],
componentRestrictions: {
country: 'dk'
}
});
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocompleteFrom.addListener('place_changed', fillInAddress);
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocompleteFrom.getPlace();
console.log(place);
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 then fill-in 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;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>address</label><input id="fromInput" /><br />
<label>postal code</label><input id="postal_code" />
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places"></script>