Friday, March 18, 2016

Developers: Saving Google API Credits with Autocomplete

There are a lot of winners with Google's new API pricing. However, if your app is using the whole suite of mapping functionality and you have a lot of users you might find your pool will start declining fast. Two functions that will draw directly on your pool and are not subject to the daily free quota is autocomplete and place search.

If you use your Google licence with the Scribble Maps API we do some of these optimizations out of the box, but if you are building your own custom implementation directly on top of the Google Maps API, there is a simple update you can do to save you some autocomplete credits.

The standard auto-complete functionality will send out an auto-complete request with every change in the input. It's possible to cut the amount of credits used significantly by putting in a timeout when the input changes.

Here is a very basic example.

 var acTimeOut;  
 textSearchInput.onkeyup = function() {  
 acTimeout = setTimeout(function() {  
 //put auto-complete calls in here  
 }, 250);  

So every time a user starts typing in the input the autocomplete will not fire until there is a momentary delay. The delay of 250ms can be reduced to make the autocomplete fire more often. If the user quickly types "Toronto", only one auto-complete call will be executed instead of 8 when the user hesitates.

We find the timed delay works the best. A critical point to this is to make sure that the user interface indicates that a search is going on as they are typing. In our case we use an animated spinner. This way if the user is typing quickly and not seeing results, the animated spinner will give them enough pause to see the results.

It should be noted that implementing this is compliant with their current terms of use. All this method essentially does is throttle the amount of out bound autocomplete calls from the user.