How can I reduce request quantity to GoogleMaps API with .geocomplete

53 Views Asked by At

I have text input with "geocomplete" on my web page. Every keyPress event sends request to GoogleMaps API. I would like to change this behavior in the way that request is sent each 3 character (not each letter) or set delay before request.

I tried to use geocode:beforegeocomelete_search event but it does not work.

$("input").geocomplete()
                .bind("geocode:beforegeocomelete_search", function(event, results){
                    if ( $("input").val().length < 4) {
                        throw "At least 3 characters required for request sending";
                    }
                });

Do you have any ideas on the matter?

1

There are 1 best solutions below

2
OXiGEN On

Not sure which version of geocomplete you are using. The version at https://github.com/ubilabs/geocomplete/ has a trigger() which you can call when the input meets the length requirements.

Note: the external lib does not seem to be loading in the snippet for some reason.

let geo = $('.geocomplete');

geo.geocomplete();
geo.on('input', function() {
  let el = $(this);
  
  if (el.val().length > 3) {
    el.trigger("geocode");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/ubilabs/geocomplete/master/jquery.geocomplete.min.js"></script>
<input class="geocomplete" />