对于Google Places Autocomplete V3,最好的解决方案是两个API请求。
这是小提琴
其他答案都不满足的原因是,他们要么使用jquery来模仿事件(骇客),要么使用了Geocoder或Google Places Search框,但这些框并不总是与自动填充结果匹配。相反,我们要做的是使用Google的自动完成服务,此处仅使用javascript(没有jquery)进行了详细说明
下面详细介绍了最兼容跨浏览器的解决方案,使用本机Google API生成自动完成框,然后重新运行查询以选择第一个选项。
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&language=en"></script>
Java脚本
var $ = document.querySelector.bind(document);
function autoCallback(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
pacInput.className = 'error';
return;
}
pacInput.className = 'success';
pacInput.value = predictions[0].description;
}
function queryAutocomplete(input) {
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
input: input,
componentRestrictions: {
country: 'us'
}
}, autoCallback);
}
function handleTabbingOnInput(evt) {
if (evt.target.id == "pac-input") {
evt.target.className = '';
if (evt.which == 9 || evt.keyCode == 9) {
queryAutocomplete(evt.target.value);
}
}
}
var pacInput = $('#pac-input');
pacInput.focus();
var options = {
componentRestrictions: {
country: 'us'
}
};
var autocomplete = new google.maps.places.Autocomplete(pacInput, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var result = autocomplete.getPlace();
if (typeof result.address_components == 'undefined') {
queryAutocomplete(result.name);
} else {
console.log(result.address_components);
}
});
if (document.addEventListener) {
document.addEventListener('keydown', handleTabbingOnInput, false);
} else if (document.attachEvent) {
document.attachEvent("onsubmit", handleTabbingOnInput);
}
var standardForm = $('#search-shop-form');
if (standardForm.addEventListener) {
standardForm.addEventListener("submit", preventStandardForm, false);
} else if (standardForm.attachEvent) {
standardForm.attachEvent("onsubmit", preventStandardForm);
}
的HTML
<form id="search-shop-form" class="search-form" name="searchShopForm" action="/impl_custom/index/search/" method="post">
<label for="pac-input">Delivery Location</label>
<input id="pac-input" type="text" placeholder="Los Angeles, Manhattan, Houston" autocomplete="off" />
<button class="search-btn btn-success" type="submit">Search</button>
</form>
唯一的麻烦是,尽管信息相同,但本机实现会返回不同的数据结构。相应地调整。