Introduction
Autocomplete is a feature of the Places library in the Google 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.
Getting started
Before using the Places library in the Google Maps JavaScript API, first ensure that the Google Places API Web Service is enabled in the Google API Console, in the same project you set up for the Google Maps JavaScript API.
To view your list of enabled APIs:
- Go to the Google API Console.
- Click the Select a project button, then select the same project you set up for the Google Maps JavaScript API and click Open.
- From the list of APIs on the Dashboard, look for Google Places API Web Service.
- 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 Google Places API Web Service, then select it from the results list.
- Select ENABLE. When the process finishes, Google Places API Web Service 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:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
See the Libraries Overview for more information.
Usage limits and policies
Quotas
The Google Places API Web Service and Place Autocomplete share a usage quota as described in the Usage Limits documentation for Google Places API Web Service. These usage limits also apply when using the Places Library in the Google Maps JavaScript API. The daily usage is calculated as the sum of client-side and server-side requests combined.
Policies
Use of the Places Library in the Google Maps JavaScript API must be in accordance with the policies described for the Google Places API Web Service.
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:
-
Autocompleteadds 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. -
SearchBoxadds a text input field to your web page, in much the same way asAutocomplete. The differences are as follows:- The main difference lies in the
results that appear in the pick list.
SearchBoxsupplies an extended list of predictions, which can include places (as defined by the Google 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. SearchBoxoffers fewer options thanAutocompletefor restricting the search. In the former, you can bias the search towards a givenLatLngBounds. In the latter, you can restrict the search to a particular country and particular place types, as well as setting the bounds.
- The main difference lies in the
results that appear in the pick list.
- You can create an
AutocompleteServiceobject to retrieve predictions programmatically. CallgetPlacePredictions()to retrieve matching places, or callgetQueryPredictions()to retrieve matching places plus suggested search terms. Note:AutocompleteServicedoes 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.
Figure 1 shows an autocomplete text field, and the pick list of place predictions supplied as the user enters the search query:
When the user selects an address from the pick list, your application can populate the address form:
See an address form in action: View example (places-autocomplete-addressform.html).
Read on to see how to add autocomplete to your web page.
Example: Autocomplete for map controls
Autocomplete is useful for prompting users for information as part of a map application, as shown in figure 3:
See it in action: View example (places-autocomplete-hotelsearch.html).
Read on to see how to add autocomplete to your web page.
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
Google Places API).
The Autocomplete constructor takes two arguments:
- An HTML
inputelement of typetext. This is the input field that the autocomplete service will monitor and attach its results to. - An
optionsargument, which can contain the following properties:- An array of
typesspecifies 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 thegeocodeandestablishmenttypes, but note that this will have the same effect as specifying no types. The supported types are:geocodeinstructs the Places service to return only geocoding results, rather than business results.addressinstructs the Places service to return only geocoding results with a precise address.establishmentinstructs the Places service to return only business results.- the
(regions)type collection instructs the Places service to return any result matching the following types:localitysublocalitypostal_codecountryadministrative_area1administrative_area2
- the
(cities)type collection instructs the Places service to return results that match eitherlocalityoradministrative_area3.
boundsis agoogle.maps.LatLngBoundsobject specifying the area in which to search for places. The results are biased towards, but not restricted to, places contained within these bounds.strictBoundsis abooleanspecifying whether the API must return only those places that are strictly within the region defined by the givenbounds. The API does not return results outside this region even if they match the user input.componentRestrictionscan be used to restrict results to specific groups. Currently, you can usecomponentRestrictionsto 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.placeIdOnlycan be used to instruct theAutocompletewidget to retrieve only Place IDs. On callinggetPlace()on theAutocompleteobject, thePlaceResultmade available will only have theplace id,typesandnameproperties set. You can use the returned place ID with calls to the Places, Geocoding, Directions or Distance Matrix services.
- An array of
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
Autocompleteobject. - 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.
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.
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('searchTextField');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
Change the bounds of an existing Autocomplete
Call setBounds() to change the search area on an existing
Autocomplete.
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
View example (places-autocomplete-addressform.html).
Set the bounds to the map's viewport
Use bindTo() to bias the results to the map's viewport,
even while that viewport changes.
autocomplete.bindTo('bounds', map);
Restrict the search to the bounds
Set the strictBounds option to restrict the results to the given bounds,
even while the viewport changes.
autocomplete.setOptions({strictBounds: true})
View example (places-autocomplete.html).
Restrict the search to a specific country
Use the componentRestrictions option to restrict the
autocomplete search to a particular country. The following code restricts the
results to cities within France.
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'fr'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
The following example allows the user to choose a country, then restricts the autocomplete results to that country.
// Set the country restriction based on user input.
// Also center and zoom the map on the given country.
function setAutocompleteCountry() {
var country = document.getElementById('country').value;
if (country == 'all') {
autocomplete.setComponentRestrictions([]);
map.setCenter({lat: 15, lng: 0});
map.setZoom(2);
} else {
autocomplete.setComponentRestrictions({'country': country});
map.setCenter(countries[country].center);
map.setZoom(countries[country].zoom);
}
clearResults();
clearMarkers();
}
View example (places-autocomplete-hotelsearch.html).
The following example specifies a number of countries in the componentRestrictions option:
View example (places-autocomplete-multiple-countries.html).
Customize the placeholder text for Autocomplete
By default, the text field created by the autocomplete service contains
standard placeholder text. To modify the text, set the
placeholder attribute on the input element:
<input id="searchTextField" type="text" size="50" placeholder="Anything you want!">
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. You can call
getPlace() on the Autocomplete object, to retrieve
a PlaceResult object.
By default, autocomplete will give you the full address as a single line of
text. For an address form, it is useful to get the address in structured
format. You can use Autocomplete.getPlace() to retrieve the full
details for each autocomplete prediction, including the structured
address.
If you use the placeIdOnly option, the Autocomplete object will not
get place details, as the PlaceResult object has only the place_id,
types and name properties set.
To get place details, retrieve a PlaceResult object by calling
getPlace() on the Autocomplete object when you get the
place_changed event. You could then use geocoding to get the location coordinates,
or the Places service to get more information on the selected place.
For more information about the PlaceResult object, refer to
the documentation on
place detail results.
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 fill 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;
}
}
}
View example (places-autocomplete-addressform.html).
Add SearchBox for autocompleting search terms
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 Google 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.
The SearchBox constructor takes two arguments:
- An HTML
inputelement of typetext. This is the input field that theSearchBoxservice will monitor and attach its results to. - An
optionsargument, which can contain theboundsproperty:boundsis agoogle.maps.LatLngBoundsobject 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.
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('searchTextField');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
Change the search area for SearchBox
To change the search area for an existing SearchBox, call
setBounds() on the SearchBox object and pass the
relevant LatLngBounds object.
View example (places-searchbox.html).
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.
For more information about the PlaceResult object, refer to
the documentation on
place detail results.
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
View example (places-searchbox.html).
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 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.
Both of the above methods return an array of five prediction objects of the following form:
descriptionis the matched prediction.idcontains a unique identifier denoting this place. This identifier may not be used to retrieve information about this place, but can be used to consolidate data about this place, and to verify the identity of a place across separate searches. As IDs can occasionally change, it's recommended that the stored ID for a place be compared with the ID returned in later Details requests for the same place, and updated if necessary. Note: Theidis deprecated in favor ofplace_id, as described in the deprecation notice on this page.matched_substringscontains 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.lengthis the length of the substring.offsetis the character offset, measured from the beginning of the description string, at which the matched substring appears.
place_idis a textual identifier that uniquely identifies a place. To retrieve information about the place, pass this identifier in theplaceIdfield of a Place Details request. Learn more about how to reference a place with a place ID.referencecontains a token that can be used to query the Details service in future. This token may differ from the reference used in the request to the Details service. It is recommended that stored references for places be regularly updated. Although this token uniquely identifies the place, the converse is not true: a place may have many valid reference tokens. Note: Thereferenceis deprecated in favor ofplace_id, as described in the deprecation notice on this page.termsis an array containing elements of the query. For a place, each element will typically make up a portion of the address.offsetis the character offset, measured from the beginning of the description string, at which the matched substring appears.valueis the matching term.
The example below executes a query prediction request for the phrase 'pizza near' and displays the result in a list.
// This example retrieves autocomplete predictions programmatically from the
// autocomplete service, and displays them as an HTML list.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initService() {
var displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
predictions.forEach(function(prediction) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(prediction.description));
document.getElementById('results').appendChild(li);
});
};
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: 'pizza near Syd' }, displaySuggestions);
}
<div id="right-panel"> <p>Query suggestions for 'pizza near Syd':</p> <ul id="results"></ul> </div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#right-panel {
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel select, #right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initService"
async defer></script>
// This example retrieves autocomplete predictions programmatically from the
// autocomplete service, and displays them as an HTML list.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initService() {
var displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
predictions.forEach(function(prediction) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(prediction.description));
document.getElementById('results').appendChild(li);
});
};
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: 'pizza near Syd' }, displaySuggestions);
}
