Google Maps API: How do you ensure that the Google Maps Autocomplete text is an actual address before submitting? [duplicate]

橙三吉。 提交于 2020-11-25 03:51:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!