Autocomplete for Addresses and Search Terms

Note: Server-side
libraries

This page describes the client-side library available with
the Maps JavaScript API. If you want to work with the
Places API web service on your server, take a look at the
Node.js Client for Google Maps Services. The page at
that link also introduces the Java Client,
Python Client and Go Client for Google Maps Services.

Introduction

Autocomplete is a feature of the Places library in the
Maps JavaScript API. You can use autocomplete to give your
applications the type-ahead-search behavior of the Google Maps search field.
When a user starts typing an address, autocomplete will fill in the rest.

Note: As defined by the Places API,
a 'place' can be an establishment, a geographic location, or a prominent
point of interest.

Getting started

Before using the Places library in the Maps JavaScript API, first ensure
that the Places API is enabled in the Google Cloud Platform Console, in the same
project you set up for the Maps JavaScript API.

Click the Select a project button, then select the same project you set up
for the Maps JavaScript API and click Open.

From the list of APIs on the Dashboard, look for
Places API.

If you see the API in the list, you’re all set. If the API is not listed,
enable it:

At the top of the page, select ENABLE API to display the
Library tab. Alternatively, from the left side menu,
select Library.

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.

Loading the library

The Places service is a self-contained library, separate from the main
Maps JavaScript API code. To use the functionality contained
within this library, you must first load it using the libraries
parameter in the Maps API bootstrap URL:

Summary of classes

The API offers two types of autocomplete widgets, which you can add via
the Autocomplete and SearchBox classes respectively.
In addition, you can use the AutocompleteService class to
retrieve autocomplete results programmatically.

Below is a summary of the classes available:

Autocomplete adds a text input field to your web page,
and monitors that field for character entries. 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, information
about the place is returned to the autocomplete object, and can be retrieved
by your application. See the details below.

SearchBox adds a text input field to your web page, in much
the same way as Autocomplete. The differences are as follows:

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. For example, if the user
enters 'pizza in new', the pick list may include the phrase
'pizza in New York, NY' as well as the names of various pizza
outlets.

SearchBox offers fewer options than
Autocomplete for restricting the search. In the former, you
can bias the search towards a given LatLngBounds. In the
latter, you can restrict the search to a particular country and particular
place types, as well as setting the bounds.

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.
Note: 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. See the
details below.

The rest of this page provides example use cases, and details on using the
above classes.

How to use Autocomplete

This video shows you how to use
Autocomplete, including demos and code samples.

Example: Autocomplete for address forms

Does your application include an address form, such as the shipping address
for an online order, a credit card billing address, or a taxi booking form?
Autocomplete can help users supply the details.

Hint: You can use Place Autocomplete even
without a map. If you do show a map, it must be a Google map.

Figure 1 shows an autocomplete text field, and the pick list of place
predictions supplied as the user enters the search query:

Figure 1: Autocomplete text field and pick listNote: When you display predictions from
Place Autocomplete, you must include the
'powered
by Google' logo. This logo is included in the results list by
default, as shown in the above example.

When the user selects an address from the pick list, your application can
populate the address form:

Add Autocomplete for places and addresses

Autocomplete creates a text input field on your web page,
supplies predictions of places in a UI pick list, and returns place details
in response to a getPlace() request. Each entry in
the pick list corresponds to a single place (as defined by the
Places API).

The Autocomplete constructor takes two arguments:

An HTML input element of type text. This is
the input field that the autocomplete service will monitor and attach its
results to.

An options argument, which can contain the following
properties:

An array of types specifies an explicit
type or a type collection, as listed in the supported types below. If
nothing is specified, all types are returned. In general only a single
type is allowed. The exception is that you can safely mix the
geocode and establishment
types, but note that this will have the same effect as specifying no types.
The supported types are:

geocode instructs the Places service to
return only geocoding results, rather than business results.

address instructs the Places service to
return only geocoding results with a precise address.

establishment instructs the Places service to return
only business results.

the (regions) type collection instructs the Places
service to return any result matching the following types:

locality

sublocality

postal_code

country

administrative_area1

administrative_area2

the (cities) type collection instructs the Places
service to return results that match either locality or
administrative_area3.

bounds is a google.maps.LatLngBounds
object specifying the area in which to search for places. The results
are biased towards, but not restricted to, places contained within
these bounds.

strictBounds is a boolean specifying whether
the API must return only those places that are strictly within the region
defined by the given bounds. The API does not return results
outside this region even if they match the user input.

componentRestrictions can be used to restrict results to
specific groups. Currently, you can use
componentRestrictions to filter by up to 5 countries. Countries
must be passed as as a two-character, ISO 3166-1 Alpha-2 compatible
country code. Multiple countries must be passed as a list of country codes.

placeIdOnly can be used to instruct the
Autocomplete widget to retrieve only Place IDs. On calling
getPlace() on the Autocomplete object, the
PlaceResult made available will only have the place id,
types and name properties set. You can use the returned
place ID with calls to the Places, Geocoding, Directions or Distance Matrix
services.
Note: The name property will contain the
description from Places Autocomplete predictions. You can read more about the
description in the
Places Autocomplete documentation.

Set biases and search-area boundaries for
Autocomplete

You can bias the autocomplete results to favor an approximate
location or area, in the following ways:

Set the bounds on creation of the Autocomplete object.

Change the bounds on an existing Autocomplete.

Set the bounds to the map's viewport.

Restrict the search to the bounds.

Restrict the search to a specific country.

Details are in the sections below.

Note: If you do not supply any bounds or a
map viewport, the API will attempt to detect the user's location from their
IP address, and will bias the results to that location.

Set the bounds on creation of the Autocomplete object

The example below uses the bounds and types
options to request businesses of type 'establishment,' favoring those
within the specified geographic area.

Note: The default placeholder text is localized automatically. If you
specify your own placeholder value, you must handle the localization of that
value in your application. For information on how the Google Maps
JavaScript API chooses the language to use, please read the documentation on
localization.

Get place information from Autocomplete

When a user selects a place from the predictions attached to the autocomplete
text field, the service fires a place_changed event. To get place
details:

Create an event handler for the place_changed event, and call addListener()
on the Autocomplete object to add the handler.

By default, when a user selects a place, autocomplete returns all of the
available data fields for the selected place, and you will be billed accordingly.
Use Autocomplete.setFields()
to specify which place data fields to return. Read more about the
PlaceResult object, including a list of place data fields that
you can request. To avoid paying for data that you don't need, be sure to use Autocomplete.setFields() to specify
only the place data that you will use.

IMPORTANT: It is not recommended to use autocomplete to refresh Place IDs, since each session
will result in a charge. Instead, call getDetails(),
and specify only the place_id field.

For address forms, it is useful to get the address in structured format. To
return the structured address for the selected place, call
Autocomplete.setFields()
and specify the address_components field.

The following example uses autocomplete to fill the fields in an address
form.

function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}

Add SearchBox for autocompleting search terms

By default, when a user selects a place, SearchBox returns all of the
available data fields for the selected place, and you will be billed accordingly.
There is no way to constrain SearchBox requests to only return specific fields.
To keep from requesting (and paying for) data that you don't need, use the
Autocomplete widget instead.

The SearchBox allows users to perform a text-based geographic
search, such as 'pizza in New York' or 'shoe stores near robson street'.
You can attach the SearchBox to a text field and, as
text is entered, the service will return predictions in the
form of a drop-down pick list.

SearchBox supplies an extended list of predictions, which
can include places (as defined by the Places API) plus suggested search
terms. For example, if the user enters 'pizza in new', the pick list may
include the phrase 'pizza in New York, NY' as well as the names of various
pizza outlets. When a user selects a place from the list,
information about that place is returned to the SearchBox object, and can be
retrieved by your application.

Note: When you display predictions from
the Google Places search box, you must include the
'powered
by Google' logo. This logo is included in the results list by
default, for your convenience.

The SearchBox constructor takes two arguments:

An HTML input element of type text. This is
the input field that the SearchBox service will monitor and
attach its results to.

An options argument, which can contain the
bounds property:
bounds is a google.maps.LatLngBounds
object specifying the area in which to search for places. The results
are biased towards, but not restricted to, places contained within
these bounds.

The following code uses the bounds parameter to bias the results
towards places within a particular geographic area, specified via
laitude/longitude coordinates.

Change the search area for SearchBox

Get SearchBox information

When the user selects an item from the predictions attached to the search
box, the service fires a places_changed event. You can
call getPlaces() on the SearchBox object, to
retrieve an array containing several predictions, each of which is a
PlaceResult object.

Style the Autocomplete and SearchBox widgets

By default, the UI elements provided by Autocomplete and
SearchBox are styled for inclusion on a Google map. You may want
to adjust the styling to suit your own site. The following CSS classes are
available. All classes listed below apply to both the
Autocomplete and the SearchBox widgets.

CSS classes for Autocomplete and SearchBox widgets

CSS class

Description

pac-container

The visual element containing the list of predictions returned by the
Place Autocomplete service. This list appears as a dropdown list below the
Autocomplete or SearchBox widget.

pac-icon

The icon displayed to the left of each item in the list of
predictions.

pac-item

An item in the list of predictions supplied by the
Autocomplete or SearchBox widget.

pac-item:hover

The item when the user hovers their mouse pointer over it.

pac-item-selected

The item when the user selects it via the keyboard. Note: Selected items
will be a member of this class and of the pac-item class.

pac-item-query

A span inside a pac-item that is the main part of the
prediction. For geographic locations, this contains a place name, like
'Sydney', or a street name and number, like '10 King Street'. For
text-based searches such as 'pizza in New York', it contains the full text
of the query. By default, the pac-item-query is colored
black. If there is any additional text in the pac-item, it is
outside pac-item-query and inherits its styling from
pac-item. It is colored gray by default. The additional text
is typically an address.

pac-matched

The part of the returned prediction that matches the user’s input. By
default, this matched text is highlighted in bold text. Note that the
matched text may be anywhere within pac-item. It is not
necessarily part of pac-item-query, and it could be partly
within pac-item-query as well as partly in the remaining text
in pac-item.

Retrieve predictions from the autocomplete
service

To retrieve predictions programmatically, use the
AutocompleteService class. AutocompleteService
does not add any UI controls. Instead, it returns an array of prediction
objects, each containing the text of the prediction, 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.

AutocompleteService exposes the following methods:

getPlacePredictions() returns place predictions.
Note: A 'place' can be an establishment, geographic location, or prominent
point of interest, as defined by the Places API.

getQueryPredictions() returns an extended list of
predictions, which can include places (as defined by the Places API)
plus suggested search terms. For example, if the user
enters 'pizza in new', the pick list may include the phrase
'pizza in New York, NY' as well as the names of various pizza outlets.

matched_substrings contains a set of substrings in the
description that match elements in the user's input. This is useful for
highlighting those substrings in your application. In many cases, the
query will appear as a substring of the description field.

length is the length of the substring.

offset is the character offset, measured from the
beginning of the description string, at which the matched substring
appears.

Session tokens

Tip: If your app is using the
Autocomplete Widget
you don't need to implement sessions, as the widget handles sessions
automatically in the background.

AutocompleteService.getPlacePredictions()
uses session tokens 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.
Once a session has concluded, the token is no longer valid; your app must
generate a fresh token for each session. We recommend using session tokens for
all autocomplete sessions. If the sessiontoken parameter is
omitted, or if you reuse a session token, the session is charged as if no
session token was provided (each request is billed separately).

You can use the same session token to make a single
Place Details
request on the place that results from a call to AutocompleteService.getPlacePredictions().
In this case, the autocomplete request is combined with the Place Details
request, and the call is charged as a regular Place Details request (the
autocomplete request is free).

The following example shows creating a session token, then passing it in an
AutocompleteService (the displaySuggestions()
function has been omitted for brevity):