Chat with usChat with us
EN

How to Implement and Optimise Google Place Autocomplete with Places Library

Image


The Google Places API returns information and predictions about places, such as businesses, addresses and points of interest . The service can be used to provide an autocomplete functionality for text-based geographic searches by returning places while a user types. Google provides a Places library, through the Maps Javascript API.


This blog post focuses on the usage of this library and how you can implement Google Place Autocomplete yourself using the API.

Implementing autocomplete with the Google Places API

How to enable the Google Places API and get the Google Places API key

Before using the Places library in the Maps JavaScript API, you must first enable the Places API in the Google Cloud Platform Console. You can do this by following these steps:


  1. Go to the Google Cloud Platform Console.
  2. Either create a new project or select an existing project.
  3. At the top of the page, click on the button ENABLE APIS AND SERVICES.
  4. Search for Places API, then select it from the results list.
  5. Select ENABLE. When the process finishes, the Places API will appear in the list of APIs on the Dashboard.

Don’t forget to apply application restrictions (to limit usage for the dedicated APIs - or at least the Places API) and API restrictions (to enable the use of this API through specific domains). We explain how to restrict a Google Places API key to a specific domain in this article.


Discover other solutions: Woosmap Localities or  Woosmap Address Finder.

How to load the Google Places 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. You can do this using the following code:

<script type= "text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

Now that we have covered how to enable the Google Places API and load the library, let’s take a look at the widgets that the Places API offers.

Widgets for the Google Places API

The Places API offers two types of autocomplete widgets, which you can add via the Autocomplete and SearchBox classes respectively.

The Autocomplete Widget

autocomplete=new google.maps.places.Autocomplete(input, options);

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 are 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 “Old Coff” and select the first item in the pick list (Old Coffee House). The results are biassed towards the current map bounds using autocomplete.bindTo('bounds', map). To instruct the Places Autocomplete service to return only results within that region, you should set the strictbounds: true option.

The SearchBox Widget

searchBox = new google.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.


Learn how to add a map to a webpage

How to create an AutocompleteService object

service = new google.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 as well as 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 thanthe Autocomplete and SearchBox features described above offer.


To get the location and more information about any of the places which are returned (for example, when a user selects the place in the pick list), you need to send a Place Details request with getDetails(request, callback) specifying the place_id and your desired fields.


In the below sample, search for “Old Coff” and select the first item in the pick list (Old Coffee House).

How to optimise your usage cost of Autocomplete in the Google Places API

There are several different solutions to help you reduce the cost of your Google Places licence.

Data return for specific fields in detailed location queries

When the Places Autocomplete service returns results from a search, it places them within a predictions array. Each prediction result contains the following fields: description, place_id, terms, types, matched_substrings, structured_formatting. You can read more about the fields included in prediction results here.


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 are billed for all of them, even the ones you don’t need. You can customise Place Detail requests to return data only for specific fields used in your application and, which will decrease the cost of your Places API License. These fields are divided into three categories: Basic, Contact, and Atmosphere. Let’s take a closer look at what is included in each one.

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 can I specify my desired data?

For example, to retrieve only the 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 the getDetails(request, callback) and specify the fields in your request parameter.

let request = {

placeId: place_id,

fields: ['geometry']

}

Session token or per query

If you are 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, which can 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’s 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.let sessionToken = new google.maps.places.AutocompleteSessionToken();// Pass the token to the autocomplete service.let autocompleteService = new google.maps.places.AutocompleteService();autocompleteService.getPlacePredictions({  input: 'Coffee near Lond',  sessionToken: sessionToken}, displaySuggestions);

How to use the Geocoding API

If your application handles user-typed addresses, the addresses are sometimes ambiguous (incomplete, misspelt, 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 other desired fields (instead of AutocompleteService.getDetails()). See Geocoding API best practices.

Using 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 a parameter will not be triggered. It will be called only after the debounce function stops being called for an elapsed time (in milliseconds).

function debounce(func, wait, immediate) {    var timeout;    return function() {        var context = this, args = arguments;        var later = function() {            timeout = null;            if (!immediate) func.apply(context, args);        };        var callNow = immediate && !timeout;        clearTimeout(timeout);        timeout = setTimeout(later, wait);        if (callNow) func.apply(context, args);    };};

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() {    let value = this.value;    if (value.length > 2) {       //call here autocompleteService.getPlacePredictions()     }}, 150)); 

Using Google Places 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 of your store's 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 Store Search API to achieve this.


Call to action: Learn more about our Store Search API


To easily implement such a solution, have a look at Woosmap MultiSearch Lib. This small JavaScript library is designed to return location suggestions by calling several autocomplete services. It enables you to combine stores search and Google Places APIs (Places Autocomplete and Places Details). Moreover, the library natively implements the debounce and minChars mechanisms.


If your users are more likely to search for specific postal codes or localities, MultiSearch can also retrieve suggestions from Woosmap Localities.


Create a free Woosmap account for your organisation

How MultiSearch combines autocomplete services?

Autocomplete services are requested in your desired order.


By comparing the user input to the returned results and computing a string matching score between these two values, the library can automatically switch to the next autocomplete service and thereby provide suggestions that better suit your needs.


For more details, read our fallback autocomplete services concept documents.

Fallback Example with MultiSearch

The following autocomplete example is for Starbucks coffee shops. If no results are available (insufficient matching score between the field name of Starbucks coffee shops and the user input), a Google Places Autocomplete is performed.


In the sample below, search for "London" and select one of the coffee shops suggestions in the pick list.


If you search for "Coleman Coffee", the autocomplete will fall back on Google Places (there is no Starbucks coffee with this name).

Google Place Autocomplete Best Practices

To optimise your usage of Google Place Autocomplete, we recommend following these 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 your store's information if the first use case is to help users find them.

The last example implements Woosmap MultiSearch with Google AutocompleteService, per Session billing, Debounce, and autocomplete on Stores before falling back to Google. This could be a good entry point for dealing with Google Place Autocomplete.

Conclusion

We have now covered how to implement the Google Places API and some strategies to ensure you receive the data you are looking for while optimising your costs.


If you have any questions about using autocomplete with the Google Places API, please don’t hesitate to reach out to us through the contact page. We are always interested to hear your feedback and suggestions!


Read our case studies from the retail sector!