Place Autocomplete

The autocomplete service in the Google Places API 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 and points of interest.

You can add autocomplete to your app in the following ways:

Add an autocomplete widget

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:

Option 1: Embed a PlaceAutocompleteFragment or a SupportPlaceAutocompleteFragment

To add a PlaceAutocompleteFragment to your app, take the following steps:

  1. Add a fragment to your activity's XML layout.
  2. Add a listener to your activity or fragment.

Add PlaceAutocompleteFragment to an activity

To add PlaceAutocompleteFragment to an activity, add a new fragment named com.google.android.gms.location.places.ui.PlaceAutocompleteFragment to an XML layout. For example:

<fragment
  android:id="@+id/place_autocomplete_fragment"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
  />

Add a PlaceSelectionListener to an activity

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 PlaceAutocompleteFragment:

PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
    @Override
    public void onPlaceSelected(Place place) {
        // TODO: Get info about the selected place.
        Log.i(TAG, "Place: " + place.getName());
    }

    @Override
    public void onError(Status status) {
        // TODO: Handle the error.
        Log.i(TAG, "An error occurred: " + status);
    }
  });

Use SupportPlaceAutocompleteFragment (older platforms)

The Google Places API requires API level 12 or higher for the support of PlaceAutocompleteFragment objects. If you are targeting an application earlier than API level 12, you can access the same functionality through the SupportPlaceAutocompleteFragment class. You must also include the Android v4 Support Library. To support Android versions earlier than API level 12, follow these steps:

  • Extend FragmentActivity or AppCompatActivity in your main activity.
  • Use SupportPlaceAutocompleteFragment instead of PlaceAutocompleteFragment.
  • Use getSupportFragmentManager() instead of getFragmentManager().

If your fragment is nested within another fragment, your app must also forward onActivityResult() calls from the containing fragment to work around a known limitation of android.support.v4.app.Fragment. This is shown in the following snippet:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    autocompleteFragment.onActivityResult(requestCode, resultCode, data);
}

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.

To launch the autocomplete widget using an intent, follow these steps:

  1. Use PlaceAutocomplete.IntentBuilder to create an intent, passing the desired PlaceAutocomplete mode. The intent must call startActivityForResult, passing in a request code that identifies your intent.
  2. Override the onActivityResult callback to receive the selected place.

Create an autocomplete intent

The example below shows using PlaceAutocomplete.IntentBuilder to create an intent to launch the autocomplete widget as an intent:

int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
...
try {
    Intent intent =
            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                    .build(this);
    startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
    // TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
    // TODO: Handle the error.
}

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:

When displayed in overlay mode, the autocomplete widget appears superimposed over the calling UI.
Figure 1: Autocomplete widget in overlay mode (MODE_OVERLAY)
When displayed in fullscreen mode, the autocomplete widget fills the entire screen.
Figure 2: Autocomplete widget in fullscreen mode (MODE_FULLSCREEN)

Override the onActivityResult callback

To receive notification when a user has selected a place, your app should override the activity's onActivityResult(), checking for the request code you have passed for your intent, as shown in the following example.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = PlaceAutocomplete.getPlace(this, data);
            Log.i(TAG, "Place: " + place.getName());
        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
            // TODO: Handle the error.
            Log.i(TAG, status.getStatusMessage());

        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}

Restrict autocomplete results

You can set the autocomplete widget to bias results to a specific geographic region, and/or filter the results to one or more place types.

Bias results to a specific region

To bias autocomplete results to a specific geographic region:

  • Call setBoundsBias() off your app's PlaceAutocompleteFragment instance, or IntentBuilder instance, passing a LatLngBounds. The following code example shows calling setBoundsBias() on a fragment instance to bias its autocomplete suggestions to a region of Sydney, Australia.
autocompleteFragment.setBoundsBias(new LatLngBounds(
        new LatLng(-33.880490, 151.184363),
        new LatLng(-33.858754, 151.229596)));

Filter results by place type

To filter autocomplete results to a specific place type, call AutocompleteFilter.Builder to create a new AutocompleteFilter, calling setTypeFilter() to set the filter to use. Then, pass the filter to a fragment or intent.

The following code example shows setting an AutocompleteFilter on a PlaceAutocompleteFragment to set a filter returning only results with a precise address.

AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
        .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
        .build();

autocompleteFragment.setFilter(typeFilter);

The following code example shows setting an AutocompleteFilter on an intent to set a filter returning only results with a precise address.

AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
        .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
        .build();

Intent intent =
        new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                .setFilter(typeFilter)
                .build(this);

For information about place types, see the guide to place types, and AutocompleteFilter.Builder.

Get 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 service by calling GeoDataApi.getAutocompletePredictions(), passing the following parameters:

  • Required: A query string containing the text typed by the user.
  • Required: A LatLngBounds object, biasing the results to a specific area specified by latitude and longitude bounds.
  • Optional: An AutocompleteFilter containing a set of place types, which you can use to restrict the results to one or more types of place. The following place types are supported:

    • TYPE_FILTER_NONE – An empty filter; all results are returned.
    • TYPE_FILTER_GEOCODE – Returns only geocoding results, rather than businesses. Use this request to disambiguate results where the specified location may be indeterminate.
    • TYPE_FILTER_ADDRESS – Returns only autocomplete results with a precise address. Use this type when you know the user is looking for a fully specified address.
    • TYPE_FILTER_ESTABLISHMENT – Returns only places that are businesses.
    • TYPE_FILTER_REGIONS – Returns only places that match one of the following types:

      • locality
      • sublocality
      • postal_code
      • country
      • administrative_area_level_1
      • administrative_area_level_2
    • TYPE_FILTER_CITIES – Returns only results matching locality or administrative_area_level_3.

For information about place types, see the guide to place types, and AutocompleteFilter.Builder.

The example below shows a simplified call to GeoDataApi.getAutocompletePredictions(). For a complete example, see the sample apps.

PendingResult<AutocompletePredictionBuffer> result =
    Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query,
        bounds, autocompleteFilter);

The API returns an AutocompletePredictionBuffer in a PendingResult. The AutocompletePredictionBuffer contains a list of AutocompletePrediction objects representing predicted places. The buffer 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 matchStyle) 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 matchStyle) returns the main text describing a place. This is usually the name of the place. Examples: "Eiffel Tower", and "123 Pitt Street".
  • getSecondaryText(CharacterStyle matchStyle) 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 Google Places API for Android, see the Place IDs and Details. For general information about place IDs, see the Place ID overview.
  • getPlaceTypes() returns the list of place types associated with this place.

Usage limits

Display attributions in your app

  • If your app uses the autocomplete service programmatically, your UI must either display a 'Powered by Google' attribution, or appear within a Google-branded map.
  • If your app uses the autocomplete widget no additional action is required (the required attribution is displayed by default).
  • If you retrieve and display additional place information after getting a place by ID, you must display third-party attributions too.

For more details, see the documentation on attributions.

Troubleshooting

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 PlaceAutocomplete.getStatus() to get the status message for the result.

Send feedback about...

location_on
Google Places API for Android