A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developers.google.com/maps/documentation/places/android-sdk/place-autocomplete below:

Autocomplete (New) | Places SDK for Android

Skip to main content Autocomplete (New)

Stay organized with collections Save and categorize content based on your preferences.

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.

You can integrate Autocomplete (New) functionality into your app in two main ways:

Note: Autocomplete (New) is available in Places SDK for Android version 3.5.0 and later. The Autocomplete (New) widget is available in Places SDK for Android version 4.3.1 and later. For more information, see Choose your SDK version. For more information about using the Kotlin APIs added in version 4.0.0, see the Reference Overview.

To more easily provide a consistent place autocomplete experience, you can add the Place Autocomplete widget to your app. The widget provides a dedicated, full-screen interface that handles user input and displays place predictions to the user while returning AutocompletePrediction objects to the app. You can then make a Place Details (New) request to get additional information about any of the place predictions.

Like when getting place predictions programmatically, the Place Autocomplete widget lets you use session tokens to group autocomplete requests into session for billing purposes. You can pass a session token when creating the intent for the widget by calling setAutocompleteSessionToken(). If you don't provide a session token, the widget will create one for you, which you can access by calling getSessionTokenFromIntent(). For more information on using session tokens, see About session tokens.

To add the Place Autocomplete widget to your app:

  1. (Optional) Define a session token. If you don't provide a session token, the widget will create one for you.

  2. Define an autocompleteIntent with the desired parameters and your session token.

  3. Define an ActivityResultLauncher for StartActivityForResult. This launcher will handle the result returned from the autocomplete activity.

  4. Handle the result in the ActivityResultLauncher's callback. This involves extracting the AutocompletePrediction and AutocompleteSessionToken (if you haven't provided your own), handling errors, and optionally making a fetchPlace() request to get additional details about a place.

  5. Launch the intent using the placeAutocompleteActivityResultLauncher

Note: Using session tokens is optional, but recommended.

The following samples demonstrate how to add the Place Autocomplete widget using both Kotlin and Java:

Kotlin
// Provide the API key that has enabled "Places API (New)" in the Google Cloud Console.
Places.initializeWithNewPlacesApiEnabled(/* Context= */ context, /* API Key= */ key)

// Optional, create a session token for Autocomplete request and the followup FetchPlace request.
val sessionToken: AutocompleteSessionToken = AutocompleteSessionToken.newInstance()

val autocompleteIntent: Intent =
    PlaceAutocomplete.createIntent(this) {
        // ... provide input params for origin, countries, types filter ...
        setAutocompleteSessionToken(sessionToken)
    }

val placeAutocompleteActivityResultLauncher: ActivityResultLauncher<Intent> =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        val intent = result.data
        if (intent != null && result.resultCode == PlaceAutocompleteActivity.RESULT_OK) {
            // get prediction object
            val prediction: AutocompletePrediction? =
                PlaceAutocomplete.getPredictionFromIntent(intent!!)

            // get session token
            val sessionToken: AutocompleteSessionToken? =
                PlaceAutocomplete.getSessionTokenFromIntent(intent!!)

            // create PlacesClient to make FetchPlace request (optional)
            val placesClient: PlacesClient = Places.createClient(this)
            val response =
                placesClient.awaitFetchPlace(prediction.placeId, Field.DISPLAY_NAME)
                {
                    sessionToken = sessionToken // optional
                }
        }
    }

// Launch Activity
placeAutocompleteActivityResultLauncher.launch(autocompleteIntent)
Java
// Provide the API key that has enabled "Places API (New)" in the Google Cloud Console.
Places.initializeWithNewPlacesApiEnabled(/* Context= */ context, /* API Key= */ key);

// Optional, create a session token for Autocomplete request and the followup FetchPlace request
AutocompleteSessionToken sessionToken = AutocompleteSessionToken.newInstance();

Intent autocompleteIntent =
    new PlaceAutocomplete.IntentBuilder()
        // ... set input params for origin, countries, types filter ...
        .setSessionToken(sessionToken) // optional
        .build(this);

ActivityResultLauncher<Intent> placeAutocompleteActivityResultLauncher =
    registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Intent intent = result.getData();
                if (result.getResultCode() == PlaceAutocompleteActivity.RESULT_OK) {
                    // get prediction object
                    AutocompletePrediction prediction =
                        PlaceAutocomplete.getPredictionFromIntent(
                            Preconditions.checkNotNull(intent));

                    // get session token
                    AutocompleteSessionToken sessionToken =
                        PlaceAutocomplete.getSessionTokenFromIntent(
                            Preconditions.checkNotNull(intent));

                    // create PlacesClient to make FetchPlace request (optional)
                    PlacesClient placesClient = Places.createClient(this);
                    FetchPlaceRequest request =
                        FetchPlaceRequest.builder(prediction.getPlaceId(),
                            Arrays.asList(Field.DISPLAY_NAME))
                            .setSessionToken(sessionToken).build();
                    Task<FetchPlaceResponse> task = placesClient.fetchPlace(request);
                }
            }
        }
    );

// Launch Activity
placeAutocompleteActivityResultLauncher.launch(autocompleteIntent);
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. 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());
        })
    );
Note: For more information on initializing 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.

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:

Required parameters Optional parameters 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());
        })
    );

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-08-14 UTC.

[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-14 UTC."],[[["Autocomplete (New) provides on-the-fly place predictions based on user input, using text search and geographic bounds for refined results."],["Developers can use parameters like `typesFilter`, `locationBias`, and `locationRestriction` to customize the search area and types of places returned."],["Responses include up to five predictions, each with details like the full place description, place ID, and distance from a specified origin."],["It's available in Places SDK for Android version 3.5.0 and later, and session tokens are recommended for billing purposes in programmatic sessions."],["Location restriction limits results to a defined area, while location bias prioritizes results within an area but allows others, and primary types filter by place categories."]]],["The Autocomplete feature returns place predictions based on a text query. It uses `PlacesClient.findAutocompletePredictions()` and `FindAutocompletePredictionsRequest` to retrieve up to five `AutocompletePrediction` objects. Key actions include setting the text query, optionally filtering by place types, countries, or location (bias/restriction). Developers can specify an origin to calculate distances and use session tokens for billing. Location restriction limits, while bias favors, results within a defined area. `FindAutocompletePredictionsRequest` builder is used to set these parameters.\n"]]


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