The autocomplete service in the Places SDK for Android returns place predictions in response to user search queries. As the user types, the autocomplete service returns suggestions for places such as businesses, addresses, plus codes, and points of interest.
You can add autocomplete to your app in the following ways:
The autocomplete widget is a search dialog with built-in autocomplete functionality. As a user enters search terms, the widget presents a list of predicted places to choose from. When the user makes a selection, a Place
instance is returned, which your app can then use to get details about the selected place.
There are two options for adding the autocomplete widget to your app:
AutocompleteSupportFragment
.To add an AutocompleteSupportFragment
to your app, take the following steps:
To add AutocompleteSupportFragment
to an activity, add a new fragment to an XML layout. For example:
<fragment android:id="@+id/autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
/>
onActivityResult
, you must call super.onActivityResult
, otherwise the fragment will not function properly.The PlaceSelectionListener
handles returning a place in response to the user's selection. The following code shows creating a reference to the fragment and adding a listener to your AutocompleteSupportFragment
:
// Initialize the AutocompleteSupportFragment. val autocompleteFragment = supportFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment // Specify the types of place data to return. autocompleteFragment.setPlaceFields(listOf(Place.Field.ID, Place.Field.NAME)) // Set up a PlaceSelectionListener to handle the response. autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener { override fun onPlaceSelected(place: Place) { // TODO: Get info about the selected place. Log.i(TAG, "Place: ${place.name}, ${place.id}") } override fun onError(status: Status) { // TODO: Handle the error. Log.i(TAG, "An error occurred: $status") } })Java
// Initialize the AutocompleteSupportFragment. AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment); // Specify the types of place data to return. autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME)); // Set up a PlaceSelectionListener to handle the response. autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(@NonNull Place place) { // TODO: Get info about the selected place. Log.i(TAG, "Place: " + place.getName() + ", " + place.getId()); } @Override public void onError(@NonNull Status status) { // TODO: Handle the error. Log.i(TAG, "An error occurred: " + status); } });Option 2: Use an intent to launch the autocomplete activity
If you want your app to use a different navigational flow (for example, to trigger the autocomplete experience from an icon rather than a search field), your app can launch autocomplete by using an intent.
Note: These steps aren't needed if you are embedding a fragment. Caution: Do NOT launch theAutcompleteActivity
directly. Instead, use an intent to launch Autocomplete
(PlaceAutocomplete
in the compatibility library).
To launch the autocomplete widget using an intent, follow these steps:
Autocomplete.IntentBuilder
to create an intent, passing the desired Autocomplete
mode.registerForActivityResult
that can be used to launch the intent and handle the user's selected place prediction in the result.The example below uses Autocomplete.IntentBuilder
to create an intent to launch the autocomplete widget as an intent:
// Set the fields to specify which types of place data to // return after the user has made a selection. val fields = listOf(Place.Field.ID, Place.Field.NAME) // Start the autocomplete intent. val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields) .build(this) startAutocomplete.launch(intent)Java
// Set the fields to specify which types of place data to // return after the user has made a selection. List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME); // Start the autocomplete intent. Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields) .build(this); startAutocomplete.launch(intent);
When using an intent to launch the autocomplete widget, you can choose from overlay or full-screen display modes. The following screenshots show each display mode respectively:
Figure 1: Autocomplete widget in OVERLAY mode Figure 2: Autocomplete widget in FULLSCREEN mode Register a callback for the intent resultTo receive a notification when the user has selected a place, define a registerForActivityResult()
launcher, which launches the activity and also handles the result as shown in the following example. If the user selected a prediction, it will be delivered in the intent contained in the result object. Since the intent was built by Autocomplete.IntentBuilder
, the method Autocomplete.getPlaceFromIntent()
can extract the Place object from it.
private val startAutocomplete = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { val intent = result.data if (intent != null) { val place = Autocomplete.getPlaceFromIntent(intent) Log.i( TAG, "Place: ${place.name}, ${place.id}" ) } } else if (result.resultCode == Activity.RESULT_CANCELED) { // The user canceled the operation. Log.i(TAG, "User canceled autocomplete") } }Java
private final ActivityResultLauncher<Intent> startAutocomplete = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK) { Intent intent = result.getData(); if (intent != null) { Place place = Autocomplete.getPlaceFromIntent(intent); Log.i(TAG, "Place: ${place.getName()}, ${place.getId()}"); } } else if (result.getResultCode() == Activity.RESULT_CANCELED) { // The user canceled the operation. Log.i(TAG, "User canceled autocomplete"); } });Getting place predictions programmatically
You can create a custom search UI as an alternative to the UI provided by the autocomplete widget. To do this, your app must get place predictions programmatically. 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 with the following parameters:
query
string containing the text typed by the user.AutocompleteSessionToken
, which groups the query and selection phases of a user 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.RectangularBounds
object, which specifies latitude and longitude bounds to constrain results to the specified region.Optional: A TypeFilter
, which you can use to restrict the results to the specified place type. The following place types are supported:
TypeFilter.GEOCODE
– Returns only geocoding results, rather than businesses. Use this request to disambiguate results where the specified location may be indeterminate.TypeFilter.ADDRESS
– Returns only autocomplete results with a precise address. Use this type when you know the user is looking for a fully specified address.TypeFilter.ESTABLISHMENT
– Returns only places that are businesses.TypeFilter.REGIONS
– Returns only places that match one of the following types:
LOCALITY
SUBLOCALITY
POSTAL_CODE
COUNTRY
ADMINISTRATIVE_AREA_LEVEL_1
ADMINISTRATIVE_AREA_LEVEL_2
TypeFilter.CITIES
– Returns only results matching LOCALITY
or ADMINISTRATIVE_AREA_LEVEL_3
.
Optional: A LatLng
specifying the location of origin for the request. When you call setOrigin()
, the service returns distance in meters (distanceMeters
) from the specified origin, for each autocomplete prediction in the response.
For information about place types, see the guide to place types.
The example below shows a complete call to PlacesClient.findAutocompletePredictions()
.
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest, // and once again when the user makes a selection (for example when calling fetchPlace()). val token = AutocompleteSessionToken.newInstance() // Create a RectangularBounds object. val bounds = RectangularBounds.newInstance( LatLng(-33.880490, 151.184363), LatLng(-33.858754, 151.229596) ) // Use the builder to create a FindAutocompletePredictionsRequest. val request = FindAutocompletePredictionsRequest.builder() // Call either setLocationBias() OR setLocationRestriction(). .setLocationBias(bounds) //.setLocationRestriction(bounds) .setOrigin(LatLng(-33.8749937, 151.2041382)) .setCountries("AU", "NZ") .setTypesFilter(listOf(PlaceTypes.ADDRESS)) .setSessionToken(token) .setQuery(query) .build() placesClient.findAutocompletePredictions(request) .addOnSuccessListener { response: FindAutocompletePredictionsResponse -> for (prediction in response.autocompletePredictions) { Log.i(TAG, prediction.placeId) Log.i(TAG, prediction.getPrimaryText(null).toString()) } }.addOnFailureListener { exception: Exception? -> if (exception is ApiException) { Log.e(TAG, "Place not found: ${exception.statusCode}") } }Java
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest, // and once again when the user makes a selection (for example when calling fetchPlace()). AutocompleteSessionToken token = AutocompleteSessionToken.newInstance(); // Create a RectangularBounds object. RectangularBounds bounds = RectangularBounds.newInstance( new LatLng(-33.880490, 151.184363), new LatLng(-33.858754, 151.229596)); // Use the builder to create a FindAutocompletePredictionsRequest. FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder() // Call either setLocationBias() OR setLocationRestriction(). .setLocationBias(bounds) //.setLocationRestriction(bounds) .setOrigin(new LatLng(-33.8749937, 151.2041382)) .setCountries("AU", "NZ") .setTypesFilter(Arrays.asList(PlaceTypes.ADDRESS)) .setSessionToken(token) .setQuery(query) .build(); placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> { for (AutocompletePrediction prediction : response.getAutocompletePredictions()) { Log.i(TAG, prediction.getPlaceId()); Log.i(TAG, prediction.getPrimaryText(null).toString()); } }).addOnFailureListener((exception) -> { if (exception instanceof ApiException) { ApiException apiException = (ApiException) exception; Log.e(TAG, "Place not found: " + apiException.getStatusCode()); } });
The API returns an FindAutocompletePredictionsResponse
in a Task
. The FindAutocompletePredictionsResponse
contains a list of 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, using CharacterStyle
. The CharacterStyle
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 the Place
object again later. For more information about place IDs in Places SDK for Android, see the Place Details. For general information about place IDs, see the Place ID overview.getPlaceTypes()
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.PlacesClient
, see Initialize the Places API client.
You can use a CancellationToken to attempt to cancel a request to any of the request classes (for example, FetchPlaceRequest
). Cancellation is done on a best-effort basis. Once a cancellation request is issued, no response will be returned. Issuing a cancellation token does NOT guarantee that a particular request will be cancelled, and you may still be charged for the request even if no response is returned.
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 programmatic autocomplete sessions (when you embed a fragment, or launch autocomplete using an intent, the API takes care of this automatically).
The Places SDK for Android 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 to fetchPlace()
to retrieve Place Details for the place that was selected by the user.
Learn more about session tokens.
Constrain autocomplete resultsYou can constrain autocomplete results to a specific geographic region, and/or filter the results to one or more place types, or to up to five countries. You can apply these constraints to the autocomplete activity, AutocompleteSupportFragment
, and programmatic autocomplete APIs.
To constrain results, do the following:
setLocationBias()
(some results from outside the defined region may still be returned).setLocationRestriction()
(only results within the defined region will be returned).setTypesFilter()
(for example, specifying TypeFilter.ADDRESS
will return only results with a precise address).setCountries()
. Countries must be passed as a two-character, ISO 3166-1 Alpha-2 compatible country code.To bias autocomplete results to a specific geographic region, call setLocationBias()
, passing a RectangularBounds
. The following code example shows calling setLocationBias()
on a fragment instance to bias its autocomplete suggestions to a region of Sydney, Australia.
autocompleteFragment.setLocationBias( RectangularBounds.newInstance( LatLng(-33.880490, 151.184363), LatLng(-33.858754, 151.229596) ) )Java
autocompleteFragment.setLocationBias(RectangularBounds.newInstance( new LatLng(-33.880490, 151.184363), new LatLng(-33.858754, 151.229596)));Restrict results to a specific region
To restrict autocomplete results to a specific geographic region, call setLocationRestriction()
, passing a RectangularBounds
. The following code example shows calling setLocationRestriction()
on a fragment instance to bias its autocomplete suggestions to a region of Sydney, Australia.
autocompleteFragment.setLocationRestriction( RectangularBounds.newInstance( LatLng(-33.880490, 151.184363), LatLng(-33.858754, 151.229596) ) )Java
autocompleteFragment.setLocationRestriction(RectangularBounds.newInstance( new LatLng(-33.880490, 151.184363), new LatLng(-33.858754, 151.229596)));
Note: This restriction is only applied to entire routes, synthetic results located outside the rectangular bounds may be returned based on a route that overlaps with the location restrict.
Filter results by place types or type collectionYou can restrict results from an autocomplete request so they only return a certain place type. Specify a filter using the place types or a type collection listed in Tables 1, 2, and 3 on Place Types. If nothing is specified, all types are returned.
To filter autocomplete results, call setTypesFilter()
to set the filter.
To specify a type or type collection filter:
Call setTypesFilter()
and specify up to five type values from Table 1 and Table 2 shown on Place Types. The type values are defined by the constants in PlaceTypes.
Call setTypesFilter()
and specify a type collection from Table 3 shown on Place Types. The collection values are defined by the constants in PlaceTypes.
Only a single type from Table 3 is allowed in the request. If you specify a value from Table 3, you cannot specify a value from Table 1 or Table 2. If you do, then an error occurs.
The following code example calls setTypesFilter()
on an AutocompleteSupportFragment
and specifies multiple type values.
autocompleteFragment.setTypesFilter(listOf("landmark", "restaurant", "store"))Java
autocompleteFragment.setTypesFilter(Arrays.asList("landmark", "restaurant", "store"));
The following code example shows calling setTypesFilter()
on an AutocompleteSupportFragment
to set a filter returning only results with a precise address by specifying a type collection.
autocompleteFragment.setTypesFilter(listOf(PlaceTypes.ADDRESS))Java
autocompleteFragment.setTypesFilter(Arrays.asList(PlaceTypes.ADDRESS, PlaceTypes.ESTABLISHMENT));
The following code example shows calling setTypesFilter()
on an IntentBuilder
to set a filter returning only results with a precise address by specifying a type collection.
val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields) .setTypesFilter(listOf(PlaceTypes.ADDRESS)) .build(this)Java
Intent intent = new Autocomplete.IntentBuilder( AutocompleteActivityMode.FULLSCREEN, fields) .setTypesFilter(Arrays.asList(PlaceTypes.ADDRESS)) .build(this);Filter results by country
To filter autocomplete results to up to five countries, call setCountries()
to set the country code. Then, pass the filter to a fragment or intent. Countries must be passed as a two-character, ISO 3166-1 Alpha-2 compatible country code.
The following code example shows calling setCountries()
on an AutocompleteSupportFragment
, to set a filter returning only results within the specified countries.
autocompleteFragment.setCountries("AU", "NZ")Java
autocompleteFragment.setCountries("AU", "NZ");Usage limits
Your usage of the Places API, including the Places SDK for Android, is no longer limited to a maximum number of requests per day (QPD). However, the following usage limits still apply:
For more details, see the documentation on attributions.
Place Autocomplete (Legacy) optimizationThis section describes best practices to help you make the most of the Place Autocomplete (Legacy) service.
Here are some general guidelines:
To optimize the cost of using the Place Autocomplete (Legacy) service, use field masks in Place Details (Legacy) and Place Autocomplete (Legacy) widgets to return only the place data fields you need.
Advanced cost optimizationConsider programmatic implementation of Place Autocomplete (Legacy) in order to access Per Request pricing and request Geocoding API results about the selected place instead of Place Details (Legacy). Per Request pricing paired with Geocoding API is more cost-effective than Per Session (session-based) pricing if both of the following conditions are met:
For help selecting the Place Autocomplete (Legacy) implementation that fits your needs, select the tab that corresponds to your answer to the following question.
Does your application require any information other than the address and latitude/longitude of the selected prediction?
Yes, needs more detailsUse session-based Place Autocomplete (Legacy) with Place Details (Legacy).
Since your application requires Place Details (Legacy) such as the place name, business status, or opening hours, your implementation of Place Autocomplete (Legacy) should use a session token (programmatically or built into the JavaScript, Android, or iOS widgets). per session plus applicable Places Data SKUs depending on which place data fields you request.1
Widget implementation
Session management is automatically built into the JavaScript, Android, or iOS widgets. This includes both the Place Autocomplete (Legacy) requests and the Place Details (Legacy) request on the selected prediction. Be sure to specify the fields
parameter in order to ensure you are only requesting the place data fields you need.
Programmatic implementation
Use a session token with your Place Autocomplete (Legacy) requests. When requesting Place Details (Legacy) about the selected prediction, include the following parameters:
fields
parameter specifying the place data fields you needGeocoding API could be a more cost-effective option than Place Details (Legacy) for your application, depending on the performance of your Place Autocomplete (Legacy) usage. Every application's Place Autocomplete (Legacy) efficiency varies depending on what users are entering, where the application is being used, and whether performance optimization best practices have been implemented.
In order to answer the following question, analyze how many characters a user types on average before selecting a Place Autocomplete (Legacy) prediction in your application.
Do your users select a Place Autocomplete (Legacy) prediction in four or fewer requests, on average?
YesImplement Place Autocomplete (Legacy) programmatically without session tokens and call Geocoding API on the selected place prediction.
Geocoding API delivers addresses and latitude/longitude coordinates. Making four Place Autocomplete (Legacy) - Per Request requests plus a Geocoding API call about the selected place prediction is less than the Per Session Place Autocomplete (Legacy) cost per session.1
Consider employing performance best practices to help your users get the prediction they're looking for in even fewer characters.
NoUse session-based Place Autocomplete (Legacy) with Place Details (Legacy).
Since the average number of requests you expect to make before a user selects a Place Autocomplete (Legacy) prediction exceeds the cost of Per Session pricing, your implementation of Place Autocomplete (Legacy) should use a session token for both the Place Autocomplete (Legacy) requests and the associated Place Details (Legacy) request per session.1
Widget implementation
Session management is automatically built into the JavaScript, Android, or iOS widgets. This includes both the Place Autocomplete (Legacy) requests and the Place Details (Legacy) request on the selected prediction. Be sure to specify the fields
parameter in order to ensure you are only requesting Basic Data fields.
Programmatic implementation
Use a session token with your Place Autocomplete (Legacy) requests. When requesting Place Details (Legacy) about the selected prediction, include the following parameters:
fields
parameter specifying Basic Data fields such as address and geometryConsider delaying Place Autocomplete (Legacy) requests
You can employ strategies such as delaying a Place Autocomplete (Legacy) request until the user has typed in the first three or four characters so that your application makes fewer requests. For example, making Place Autocomplete (Legacy) requests for each character after the user has typed the third character means that if the user types seven characters then selects a prediction for which you make one Geocoding API request, the total cost would be for 4 Place Autocomplete (Legacy) Per Request + Geocoding.1
If delaying requests can get your average programmatic request below four, you can follow the guidance for performant Place Autocomplete (Legacy) with Geocoding API implementation. Note that delaying requests can be perceived as latency by the user who might be expecting to see predictions with every new keystroke.
Consider employing performance best practices to help your users get the prediction they're looking for in fewer characters.
Performance best practicesThe following guidelines describe ways to optimize Place Autocomplete (Legacy) performance:
Although a wide variety of errors can occur, the majority of the errors your app is likely to experience are usually caused by configuration errors (for example, the wrong API key was used, or the API key was configured incorrectly), or quota errors (your app has exceeded its quota). See Usage Limits for more information about quotas.
Errors that occur in the use of the autocomplete controls are returned in the onActivityResult()
callback. Call Autocomplete.getStatus()
to get the status message for the result.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4