Implement and Optimize Autocomplete With Google Places API
In this article, see how to implement and optimize autocomplete with Google Places API.
Join the DZone community and get the full member experience.
Join For FreeThe Google Places API is a service that returns places predictions using HTTP requests. The service can be used to provide an autocomplete functionality for text-based geographic searches by returning places such as businesses, addresses, and points of interest as a user types. Google provides a Places library through the Maps Javascript API. This blog post focus on the usage of this library.
Implementing Google Places Autocomplete
Enable the Places API
Before using the Places library in the Maps JavaScript API, you must enable the Places API in the Google Cloud Platform Console.
- Go to the Google Cloud Platform Console.
- Either create a new or select an existing project.
- At the top of the page, click on the button ENABLE APIS AND SERVICES.
- Search for Places API, then select it from the results list.
- Select ENABLE. When the process finishes, Places API appears in the list of APIs on the Dashboard.
Don’t forget to apply Application restrictions (to limit usage for the dedicated APIs — at least Places API) and API restrictions (to enable the use of this API through specific domain). How to do it.
Loading the Library
In order to use autocomplete, you must first load the Google Places library using the libraries
parameter in the bootstrap URL for the Google Maps JavaScript API.
<script type= "text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Autocompletion Using the Widgets
The Places API offers two types of autocomplete widgets, which you can add via the Autocomplete
and SearchBox
classes respectively.
The Autocomplete
Widget
Autocomplete
adds a text input field on your web page. As the user enters text, autocomplete returns place predictions in the form of a dropdown pick list. When the user selects a place from the list, place details is returned in response to a getPlace()
request. Each entry in the pick list corresponds to a single place (as defined by the Places API). You can restrict the search to a particular country and particular place types, as well as setting the bounds.
In the below sample, search for “Coleman Cof” and select the first item in the pick list (Coleman Coffee Roasters). Results are biased towards with the current map bounds using autocomplete.bindTo('bounds', map)
but to instruct the Place Autocomplete service to return only results within that region, you should set the strictbounds: true
option.
The SearchBox
Widget
searchBox=newgoogle.maps.places.SearchBox(input,options);
SearchBox
adds a text input field to your web page, in much the same way as Autocomplete
. The main difference lies in the results that appear in the pick list. SearchBox supplies an extended list of predictions, which can include places (as defined by the Places API) plus suggested search terms. SearchBox
offers fewer options than Autocomplete for restricting the search. You can only bias the search towards a given LatLngBounds
.
In the below sample, search for “Coffee near Lond” and select the first suggested search term in the pick list.
Autocompletion Using the AutocompleteService
service=newgoogle.maps.places.AutocompleteService();
service.getQueryPredictions({input:'hotels near Lond'},function(predictions,status){});
You can create an AutocompleteService
object to retrieve predictions programmatically. Call getPlacePredictions()
to retrieve matching places, or call getQueryPredictions()
to retrieve matching places plus suggested search terms. AutocompleteService
does not add any UI controls.
Instead, the above methods return an array of prediction objects. Each prediction object contains the text of the prediction, as well as reference information and details of how the result matches the user input. This is useful if you want more control over the user interface than is offered by the Autocomplete and SearchBox described above.
To get the location and more information about any of the places that are returned (when a user select the place in the pick list for example), you need to send a Place Details request with getDatails(request, callback)
specifying the place_id
and wanted fields
to be returned.
In the below sample, search for “Coleman Cof” and select the first item in the pick list (Coleman Coffee Roasters).
Optimization
Here are different solutions to help you reduce the cost of your Places license.
Return Data for Specific Fields in Place Details Requests
When the Places Autocomplete service returns results from a search, it places them within a predictions array. Each prediction result contains the following fields (check here for more details): description
, place_id
, terms
, types
, matched_substrings
, structured_formatting
By default, when a user selects a place from the pick list, autocomplete returns all of the available data fields for the selected place, and you will be billed accordingly. You can customize Place Detail requests to return data for specific fields used in your application and so decrease the cost of your Places API License. These fields are divided into categories: Basic, Contact, and Atmosphere.
Basic
The Basic category includes the following fields: address_component
, adr_address
, formatted_address
, geometry
, icon
, name
, permanently_closed
, photo
, place_id
, plus_code
, type
, url
, utc_offset
, vicinity
Contact
The Contact category includes the following fields: formatted_phone_number
, international_phone_number
, opening_hours
, website
Atmosphere
The Atmosphere category includes the following fields: price_level
, rating
, review
, user_ratings_total
How to Specify Desired Data?
For example, to retrieve only geometry
field in the details response (when user select an item in the pick list), define as below:
- Places Autocomplete widget: use
autocomplete.setFields(['geometry'])
. check the jsFiddle above to see how. - Places SearchBox widget: there is no way to constrain SearchBox requests to only return specific fields.
- Places AutocompleteService: you have to use the
PlacesService
to call thegetDetails(request, callback)
and specify the fields in yourrequest
parameter.letrequest={ placeId:place_id, fields:['geometry'] }
Per Request vs Session Token
If you're using the Autocomplete Widget, you don’t need to implement sessions, as the widget handles sessions automatically in the background.
The Per Request is the default billing option when you use AutocompleteService
. Charges are applied per keystroke, that could lead to higher billings.
You should use Session Tokens when implementing AutocompleteService.getPlacePredictions()
to group together autocomplete requests for billing purposes. Session tokens group the query and selection phases of a user autocomplete search into a discrete session for billing purposes. The session begins when the user starts typing a query and concludes when they select a place. Each session can have multiple queries, followed by one place selection.
The following example shows a request using the sessiontoken parameter:
// Create a new session token.
letsessionToken=newgoogle.maps.places.AutocompleteSessionToken();
// Pass the token to the autocomplete service.
letautocompleteService=newgoogle.maps.places.AutocompleteService();
autocompleteService.getPlacePredictions({
input:'Coffee near Lond',
sessionToken:sessionToken
},displaySuggestions);
Use the Geocoding API
If your application handles user-typed addresses, the addresses are sometimes ambiguous (incomplete, misspelled, or poorly formatted). You can disambiguate addresses using Autocomplete. Then, use the place IDs to get the place locations. If you have an exact address (or close to it), however, you can reduce costs by using Geocoding instead of Autocomplete. You could, for example, use the AutocompleteService to get the exact address name and then execute a geocoding request to get the geometry and others desired fields (instead of AutocompleteService.getDetails()
). See Geocoding API best practices.
Use Debounce and minChar With AutocompleteService
The debounce function limits the rate at which a function can fire. It takes at least 2 arguments, the input function to call and a time to wait before calling it. As long as this method continues to be invoked, the function passed as parameter will not be triggered. It will be called only after the debounce function stops being called for an elapsed time (in milliseconds).
functiondebounce(func,wait,immediate){
vartimeout;
returnfunction(){
varcontext=this,args=arguments;
varlater=function(){
timeout=null;
if(!immediate)func.apply(context,args);
};
varcallNow=immediate&&!timeout;
clearTimeout(timeout);
timeout=setTimeout(later,wait);
if(callNow)func.apply(context,args);
};
};
You’ll pass the debounce function the function to execute and the fire rate limit in milliseconds. The following example call the AutocompleteService.getPlacePredictions()
on input
event of the dedicated input text only when two keystrokes are separated by at least 150ms.
autocomplete_input.addEventListener('input',debounce(function(){
letvalue=this.value;
autocompleteService.getPlacePredictions({
input:value
},displaySuggestions);
},150));
Autocomplete and SearchBox widgets do not implement a debounce method. Thus, each keystroke calls AutocompleteService.
In addition to this mechanism, you could combine your call with a minChar
parameter to only trigger the Autocomplete when the text input reaches at least X characters.
autocomplete_input.addEventListener('input',debounce(function(){
letvalue=this.value;
if(value.length>2){
//call here autocompleteService.getPlacePredictions()
}
},150));
Autocomplete on Stores
If your main goal to implement Google Places Autocomplete is to help your users find the right store for them, why not combine an autocompletion on your stores information (name and city for example) before possibly falling back to the Google Places Autocomplete. If you’re a Woosmap customer and already have your stores hosted on our own, you could use the Woosmap Search API to achieve this.
The following sample Autocomplete for coffee shops (data extracted from OSM). If no results are available, a Google places Autocomplete is performed.
In the below sample, search for “London” and select one of the coffee shop suggestions in the pick list. If you enter the text “Coleman Coffee”, the autocomplete fall back on Google Places (there is no coffee with this name in the OSM database).
Conclusion
To optimize Google Places Autocomplete, we recommend the following guidelines:
- Prefer using the
AutocompleteService
instead of the Widgets to gain fine-grained control over the available optimizations. - Use the Per Session billing option.
- Gather only required fields when getting details of a place.
- Implement Debounce and minChars mechanisms.
- Use the Geocoding API to retrieve address information instead of
getDetails()
from Autocomplete. - Alternatively, offer to autocomplete on your stores information if the first use case is to help users find them.
The last jsFiddle sample implements Woosmap autocomplete on Stores before falling back to AutocompleteService
, per Session billing, Debounce, and Geocoding API. It could be a good entry-point for dealing with Google Places Autocomplete.
If you have any questions about the content, please don’t hesitate to reach out to us through the documentation contact page. We are always interested in your suggestions and always available to satisfy you.
Further Reading
Building a Place-Based Experience With Places API and Firebase
Published at DZone with permission of Cedric Brun. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments