Google map autocomplete - maximum 3 character type

放肆的年华 提交于 2021-02-19 05:34:17

问题


I have implemented Google map with search box in it which allows user to select address by searching it.

In that search box, even if I am typing 1 character it searches.. I want user to type at least 3 characters else it should not go for search.

My JS Fiddle is: http://jsfiddle.net/upsidown/2NhsE/

How can I do this? Is Google provides that restriction?


回答1:


Google doesn't provide this option for places autocomplete element at the moment.

There is a feature requests in the public issue tracker. Have a look at issue 5831. The issue's status is Accepted, however there is no any ETA exposed. You can star this issue to add your vote and receive further updates.

Also there is a comment #15 with recommendation how to implement this using autocomplete service.


Update: 04 June 2018

This feature was marked as Won't Fix (Obsolete)

This feature request is obsoleted by the new session-based billing for Places autocomplete. Please refer to the "Place Autocomplete" section of https://cloud.google.com/maps-platform/user-guide/pricing-changes/ for more details.




回答2:


You can validate the string and rebuild the AutoComplete like this

in this case im using jQuery this API stopImmediatePropagation also about val

input.keyup(function(e){
if(input.val().length<2){
    e.stopImmediatePropagation()
}
else{
   createAutoComplete(input)
} 



回答3:


You can initialize the autocomplete after user has entered at least minimum characters. Bellow code listens to keyup events on input with jQuery. When the user types 3rd character it will initialize the autocomplete.

I think your intension is to avoid additional API requests. This should work.

window.autocompleteobj =false;

//initialize map after 2 chars are typed
$('#autocompleteinput').keyup(function(e) {
    if ($('#autocompleteinput').val().length < 3) {
        e.stopImmediatePropagation()
    } else {
        if (window.autocompleteobj == false) {
            window.autocompleteobj = new google.maps.places.Autocomplete(autocompleteinput);
            google.maps.event.addListener(autocompleteobj, 'place_changed', function() {
               //your stuff here
            });
        }
    }
});



回答4:


Check the length of text input in pac-input textbox. if the length is greater than 3, then forward that query to google maps.



来源:https://stackoverflow.com/questions/41997223/google-map-autocomplete-maximum-3-character-type

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