Autocomplete (New) returns place predictions in response to a request that includes a text search string and geographic bounds that control the search area. Autocomplete can match on full words and substrings of the input, resolving place names, addresses, and plus codes. Your application can send queries as the user types, to provide on-the-fly place and query predictions.
For example, you call Autocomplete using as input a string that contains a partial user input, "Sicilian piz", with the search area limited to San Francisco, CA. The response then contains a list of place predictions that match the search string and search area, such as the restaurant named "Sicilian Pizza Kitchen".
The returned place predictions are designed to be presented to the user to aid them in selecting the desired place. You can make a Place Details (New) request to get more information about any of the returned place predictions.
Autocomplete (New) requests
Your app can get a list of predicted place names and/or
addresses from the autocomplete API by calling
PlacesClient.findAutocompletePredictions()
,
passing a
FindAutocompletePredictionsRequest
object. The example below shows a complete call to
PlacesClient.findAutocompletePredictions()
.
Places.initializeWithNewPlacesApiEnabled(context, apiKey); final List<Field> placeFields = getPlaceFields(); LatLng center = new LatLng(37.7749, -122.4194); CircularBounds circle = CircularBounds.newInstance(center, /* radius = */ 5000); final FindAutocompletePredictionsRequest autocompletePlacesRequest = FindAutocompletePredictionsRequest.builder() .setQuery("Sicilian piz") .setRegionCode("ES") .setLocationRestriction(circle) .build()); placesClient.findAutocompletePredictions(autoCompletePlacesRequest) .addOnSuccessListener( (response) -> { List<AutocompletePrediction> predictions = response.getResult().getAutocompletePredictions(); } ).addOnFailureListener( exception -> { Log.e(TAG, "some exception happened" + exception.getMessage()); }) );
Autocomplete (New) responses
The API returns an
FindAutocompletePredictionsResponse
in a
Task
.
The
FindAutocompletePredictionsResponse
contains a list of up to five
AutocompletePrediction
objects representing predicted places. The list may be empty, if there is no
known place corresponding to the query and the filter criteria.
For each predicted place, you can call the following methods to retrieve place details:
getFullText(CharacterStyle)
returns the full text of a place description. This is a combination of the primary and secondary text. Example: "Eiffel Tower, Avenue Anatole France, Paris, France". In addition, this method lets you highlight the sections of the description that match the search with a style of your choice, usingCharacterStyle
. TheCharacterStyle
parameter is optional. Set it to null if you don't need any highlighting.getPrimaryText(CharacterStyle)
returns the main text describing a place. This is usually the name of the place. Examples: "Eiffel Tower", and "123 Pitt Street".getSecondaryText(CharacterStyle)
returns the subsidiary text of a place description. This is useful, for example, as a second line when showing autocomplete predictions. Examples: "Avenue Anatole France, Paris, France", and "Sydney, New South Wales".getPlaceId()
returns the place ID of the predicted place. A place ID is a textual identifier that uniquely identifies a place, which you can use to retrieve thePlace
object again later. For more information about place IDs in Autocomplete, see Place Details (New). For general information about place IDs, see the Place ID overview.getTypes()
returns the list of place types associated with this place.getDistanceMeters()
returns the straight-line distance in meters between this place and the origin specified in the request.
Required parameters
-
Query
The text string on which to search. Specify full words and substrings, place names, addresses, and plus codes. The Autocomplete (New) service returns candidate matches based on this string and orders results based on their perceived relevance.
To set the query parameter, call the
setQuery()
method when building theFindAutocompletePredictionsRequest
object.
Optional parameters
-
Primary types
A list of up to five type type values from types Table A or Table B used to filter the places returned in the response. A place must match one of the specified primary type values to be included in the response.
A place can only have a single primary type from types Table A or Table B associated with it. For example, the primary type might be
"mexican_restaurant"
or"steak_house"
.The request is rejected with an
INVALID_REQUEST
error if:- More than five types are specified.
- Any unrecognized types are specified.
To set the primary types parameter, call the
setTypesFilter()
method when building theFindAutocompletePredictionsRequest
object. -
Countries
Only include results from the list of specified countries, specified as a list of up to 15 ccTLD ("top-level domain") two-character values. If omitted, no restrictions are applied to the response. For example, to limit the regions to Germany and France:
If you specify both
locationRestriction
andincludedRegionCodes
, the results are located in the area of intersection of the two settings.To set the countries parameter, call the
setCountries()
method when building theFindAutocompletePredictionsRequest
object. -
Input offset
The zero-based Unicode character offset indicating the cursor position in the query. The cursor position can influence what predictions are returned. If empty, it defaults to the length of the query.
To set the input offset parameter, call the
setInputOffset()
method when building theFindAutocompletePredictionsRequest
object. Location bias or location restriction
You can specify a location bias or location restriction, but not both, to define the search area. Think of location restriction as specifying the region which the results must be within, and location bias as specifying the region that the results must be near. The key difference is that with location bias, results outside of the specified region may still be returned.
Location bias
Specifies an area to search. This location serves as a bias, not a restriction, so results outside the specified area may still be returned.
To set the location bias parameter, call the
setLocationBias()
method when building theFindAutocompletePredictionsRequest
object.Location restriction
Specifies an area to search. Results outside the specified area are not returned.
To set the location restriction parameter, call the
setLocationRestriction()
method when building theFindAutocompletePredictionsRequest
object.
Specify the location bias or location restriction region as a rectangular Viewport or as a circle.
A circle is defined by center point and radius in meters. The radius must be between 0.0 and 50000.0, inclusive. The default value is 0.0. For location restriction, you must set the radius to a value greater than 0.0. Otherwise, the request returns no results.
A rectangle is a latitude-longitude viewport, represented as two diagonally opposite
low
andhigh
points. A viewport is considered a closed region, meaning it includes its boundary. The latitude bounds must range between -90 to 90 degrees inclusive, and the longitude bounds must range between -180 to 180 degrees inclusive:- If
low
=high
, the viewport consists of that single point. - If
low.longitude
>high.longitude
, the longitude range is inverted (the viewport crosses the 180 degree longitude line). - If
low.longitude
= -180 degrees andhigh.longitude
= 180 degrees, the viewport includes all longitudes. - If
low.longitude
= 180 degrees andhigh.longitude
= -180 degrees, the longitude range is empty.
Both
low
andhigh
must be populated, and the represented box cannot be empty. An empty viewport results in an error.- If
-
Origin
The origin point from which to calculate straight-line distance to the destination (accessed using
getDistanceMeters()
). If this value is omitted, straight-line distance won't be returned. Must be specified as latitude and longitude coordinates:To set the origin parameter, call the
setOrigin()
method when building theFindAutocompletePredictionsRequest
object. -
Region code
The region code used to format the response, including address formatting, specified as a ccTLD ("top-level domain") two-character value. Most ccTLD codes are identical to ISO 3166-1 codes, with some notable exceptions. For example, the United Kingdom's ccTLD is "uk" (.co.uk) while its ISO 3166-1 code is "gb" (technically for the entity of "The United Kingdom of Great Britain and Northern Ireland").
If you specify an invalid region code, the API returns an
INVALID_ARGUMENT
error. The parameter can affect results based on applicable law.To set the region code parameter, call the
setRegionCode()
method when building theFindAutocompletePredictionsRequest
object. -
Session token
Session tokens are user-generated strings that track Autocomplete (New) calls as "sessions." Autocomplete uses session tokens to 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 programmatic autocomplete sessions (when you embed a fragment, or launch autocomplete using an intent, the API takes care of this automatically).
The Autocomplete uses a
AutocompleteSessionToken
to identify each session. Your app should pass a new session token upon beginning each new session, then pass that same token, along with a Place ID, in the subsequent call tofetchPlace()
to retrieve Place Details for the place that was selected by the user.To set the session token parameter, call the
setSessionToken()
method when building theFindAutocompletePredictionsRequest
object.For more information, see Session tokens.
Autocomplete (New) examples
Use location restriction and location bias
Autocomplete (New) uses IP biasing by default to control the search area. With IP biasing, the API uses the IP address of the device to bias the results. You can optionally use location restriction or location bias, but not both, to specify an area to search.
Location restriction specifies the area to search. Results outside the specified area are not returned. The following example uses location restriction to limit the request to a circular location restriction with a 5000-meter radius centered on San Francisco:
Places.initializeWithNewPlacesApiEnabled(context, apiKey); final List<Field> placeFields = getPlaceFields(); LatLng center = new LatLng(37.7749, -122.4194); CircularBounds circle = CircularBounds.newInstance(center, /* radius = */ 5000); final FindAutocompletePredictionsRequest autocompletePlacesRequest = FindAutocompletePredictionsRequest.builder() .setQuery("Amoeba") .setLocationRestriction(circle) .build()); placesClient.findAutocompletePredictions(autoCompletePlacesRequest) .addOnSuccessListener( (response) -> { List<AutocompletePrediction> predictions = response.getResult().getAutocompletePredictions(); } ).addOnFailureListener( exception -> { Log.e(TAG, "some exception happened" + exception.getMessage()); }) );
With location bias, the location serves as a bias which means results around the specified location can be returned, including results outside the specified area. The next example changes the previous request to use location bias:
Places.initializeWithNewPlacesApiEnabled(context, apiKey); final List<Field> placeFields = getPlaceFields(); LatLng center = new LatLng(37.7749, -122.4194); CircularBounds circle = CircularBounds.newInstance(center, /* radius = */ 5000); final FindAutocompletePredictionsRequest autocompletePlacesRequest = FindAutocompletePredictionsRequest.builder() .setQuery("Amoeba") .setLocationBias(circle) .build()); placesClient.findAutocompletePredictions(autoCompletePlacesRequest) .addOnSuccessListener( (response) -> { List<AutocompletePrediction> predictions = response.getResult().getAutocompletePredictions(); } ).addOnFailureListener( exception -> { Log.e(TAG, "some exception happened" + exception.getMessage()); }) );
Use primary types
Use the primary types parameter to restrict results from a request to be of a certain type as listed in Table A and Table B. You can specify an array of up to five values. If omitted, all types are returned.
The following example specifies a query string of "Soccer" and uses the primary
types parameter to restrict results to establishments of type
"sporting_goods_store"
:
Places.initializeWithNewPlacesApiEnabled(context, apiKey); final List<Field> placeFields = getPlaceFields(); final List<Place.Field> primaryTypes = Arrays.asList("sporting_goods_store"); LatLng center = new LatLng(37.7749, -122.4194); CircularBounds circle = CircularBounds.newInstance(center, /* radius = */ 5000); final FindAutocompletePredictionsRequest autocompletePlacesRequest = FindAutocompletePredictionsRequest.builder() .setQuery("Soccer") .setIncludedPrimaryTypes(primaryTypes) .setLocationBias(circle) .build()); placesClient.findAutocompletePredictions(autoCompletePlacesRequest) .addOnSuccessListener( (response) -> { List<AutocompletePrediction> predictions = response.getResult().getAutocompletePredictions(); } ).addOnFailureListener( exception -> { Log.e(TAG, "some exception happened" + exception.getMessage()); }) );
If you omit the primary types parameter, the results can include establishments
of a type that you may not want, such as "athletic_field"
.
Use origin
When you include the origin parameter in the request, specified as
latitude and longitude coordinates, the API includes the straight-line distance
from the origin to the destination in the response (accessed using
getDistanceMeters()
).
This example sets the origin to the center of San Francisco:
Places.initializeWithNewPlacesApiEnabled(context, apiKey); final List<Field> placeFields = getPlaceFields(); LatLng center = new LatLng(37.7749, -122.4194); CircularBounds circle = CircularBounds.newInstance(center, /* radius = */ 5000); final FindAutocompletePredictionsRequest autocompletePlacesRequest = FindAutocompletePredictionsRequest.builder() .setQuery("Amoeba") .setOrigin(center) .setLocationRestriction(circle) .build()); placesClient.findAutocompletePredictions(autoCompletePlacesRequest) .addOnSuccessListener( (response) -> { List<AutocompletePrediction> predictions = response.getResult().getAutocompletePredictions(); } ).addOnFailureListener( exception -> { Log.e(TAG, "some exception happened" + exception.getMessage()); }) );
Attributions
You can use Autocomplete (New) even without a map. If you do show a map, it must be a Google map. When you display predictions from the Autocomplete (New) service without a map, you must include the Google logo displayed inline with the search field/results. For more information, see Displaying the Google logo and attributions.