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/autocomplete below:

Place Autocomplete | Places SDK for Android

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:

Option 1: Embed an AutocompleteSupportFragment

To add an AutocompleteSupportFragment 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 AutocompleteSupportFragment to an activity

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"
  />
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 AutocompleteSupportFragment:

Kotlin
    // 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 the AutcompleteActivity directly. Instead, use an intent to launch Autocomplete (PlaceAutocomplete in the compatibility library).

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

  1. Use Autocomplete.IntentBuilder to create an intent, passing the desired Autocomplete mode.
  2. Define an activity result launcher registerForActivityResult that can be used to launch the intent and handle the user's selected place prediction in the result.
Create an autocomplete intent

The example below uses Autocomplete.IntentBuilder to create an intent to launch the autocomplete widget as an intent:

Kotlin
    // 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 result

To 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.

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

For information about place types, see the guide to place types.

The example below shows a complete call to PlacesClient.findAutocompletePredictions().

Kotlin
    // 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:

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.

Session tokens

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.

Tip: If your app is using the Autocomplete widget, you don't need to implement sessions, as the widget handles sessions automatically in the background.

Learn more about session tokens.

Constrain autocomplete results

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

Bias results to a specific region

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.

Kotlin
    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.

Kotlin
    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 collection

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

The following code example calls setTypesFilter() on an AutocompleteSupportFragment and specifies multiple type values.

Kotlin
    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.

Kotlin
    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.

Kotlin
    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.

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

Display attributions in your app

For more details, see the documentation on attributions.

Place Autocomplete (Legacy) optimization

This section describes best practices to help you make the most of the Place Autocomplete (Legacy) service.

Here are some general guidelines:

Cost optimization best practices Basic cost optimization

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 optimization

Consider 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 details

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

  1. The place ID from the Place Autocomplete (Legacy) response
  2. The session token used in the Place Autocomplete (Legacy) request
  3. The fields parameter specifying the place data fields you need
No, needs only address and location

Geocoding 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?

Yes

Implement 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.

No

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

  1. The place ID from the Place Autocomplete (Legacy) response
  2. The session token used in the Place Autocomplete (Legacy) request
  3. The fields parameter specifying Basic Data fields such as address and geometry

Consider 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 practices

The following guidelines describe ways to optimize Place Autocomplete (Legacy) performance:

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