问题
I have a Google Maps search box using autocomplete (as the user inputs text in the field, a dropdown of address suggestions appears).
I want to make sure that when a user submits the form, the text inside the field is an actual Autocomplete suggestion.
My goal is to ensure that the text entered is an actual adress, rather than a random string.
回答1:
I had a similar issue (that anything in the given field should be valid Google Maps address), and built a solution inspired from this one, that may help you. The idea is :
- when the user does something else than click on a Google Maps suggestion
- trigger the event to move focus on the first suggestion
- trigger the event to select it
I copy the result for my own code (with Jquery) :
//// Ensuring that only Google Maps adresses are inputted
function selectFirstAddress (input) {
google.maps.event.trigger(input, 'keydown', {keyCode:40});
google.maps.event.trigger(input, 'keydown', {keyCode:13});
}
// Select first address on focusout
$('#content').on('focusout', 'input#xxx__zzz', function() {
selectFirstAddress(this);
});
// Select first address on enter in input
$('#content').on('keydown', 'input#xxx__zzz', function(e) {
if (e.keyCode == 13) {
selectFirstAddress(this);
}
});
For me it works, I hope it helps !
回答2:
The following link describes an example in which you can access autocomplete suggestions: https://developers.google.com/maps/documentation/javascript/examples/places-queryprediction
来源:https://stackoverflow.com/questions/18454677/google-maps-api-how-do-you-ensure-that-the-google-maps-autocomplete-text-is-an