我正在使用 googles api places 来获取地址自动完成建议。这是我的简单工作代码:
<!DOCTYPE html>
<html>
<body>
<form>
<input id="customerAddress" name="customerAddress" required autocomplete="off" />
<input id="zip" name="zip" required readonly />
<input id="city" name="city" required readonly />
</form>
<script
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initAutocomplete&libraries=places"
async
></script>
<script>
let autocomplete;
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete(document.querySelector("#customerAddress"), {
componentRestrictions: { country: ["de", "DE"] },
fields: ["address_components", "geometry"],
types: ["address"],
});
autocomplete.addListener("place_changed", fillInAddress);
}
function fillInAddress() {
const place = autocomplete.getPlace();
var address = ""
var streetNumber = ""
for (const component of place.address_components) {
const componentType = component.types[0];
switch (componentType) {
case "route": {
address = component.long_name;
break;
}
case "street_number": {
streetNumber = component.long_name
break;
}
case "postal_code": {
document.querySelector("#zip").value = component.long_name;
break;
}
case "locality":
document.querySelector("#city").value = component.long_name;
break;
}
}
document.querySelector("#customerAddress").value = address +" "+streetNumber
}
</script>
</body>
</html>
现在我会意识到以下情况:
客户应将其地址写入“customerAddress”字段以获取建议,但地址必须包含门牌号。我该如何限制这个?
只有当客户从自动完成列表中选择了建议时,才能提交表单。如果他/她手动写了一个不在自动完成列表中的地址,那一定是一个错误