Google places autocomplete android

Android Google Places AutoComplete Feature-How to add it to your android app

In android development, searching for places around the globe has become easier and fun to implement with the Google Places SDK for Android that provides places autocomplete service.

“ 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 and points of interest.”

In this post, we will explore the different ways we can add the autocomplete search feature to an android app. They are:

  • Add as an autocomplete widget to save development time and ensure consistent user experience.
  • Get place predictions programmatically to create a customized user experience.

NOTE: You’d need to create an API Key from the google cloud platform . You also need to register the app in the Google API Console so as to get an API KEY. Once, you have your API key, you can proceed… be sure to keep it safe.

By this time you should have created an android studio project for this.

Add the following dependency to your app’s build.gradle and sync project:

Copy the API key from the google console and add it to your strings.xml folder like this:

In the activity within which you want to implement the autocomplete search feature, you’d need to initialize Places like this:

Now we’re set to add the autocomplete search feature! We would explore both options.

Using this option, you can do either of the following:

a. Embed an AutocompleteSupportFragment or

b. Use an intent to launch the autocomplete activity.

Let’s consider option a 🙂

a. Embed an AutocompleteSupportFragment

This involves just adding a fragment to your activity’s XML layout and a listener to your activity or fragment.

Add the following code to your XML layout:

Next, initialize the AutocompleteSupportFragment and set the fields to specify which types of place data to return in the activity or fragment.

That’s it! you can run your code : )

b. Use an intent to launch the autocomplete activity.

Using this approach, I prefer to have a custom search icon on the toolbar which when clicked triggers the autocomplete search feature. I presume you already know how to add a search icon to the toolbar! You can add the following codes in your menu.xml file:

In your activity, after initializing Places, you can override the onOptionsItemSelected method which has the onSearchCalled() method when the search icon is clicked.

in the onSearchCalled() method, we set the fields to specify which types of place data to return. Thereafter, we use Autocomplete.IntentBuilder to create an intent, passing the desired PlaceAutocomplete mode (full-screen, or overlay). The intent must call startActivityForResult , passing in a request code that identifies your intent.

In my case, I specified 4 types of place data to return, you can specify more or less, be sure to check the documentation for other fields.

Also of note is the AUTOCOMPLETE_REQUEST_CODE which is a constant and can be any unique number.

Override the onActivityResult callback to receive the selected place.

That’s it! you can run your code : )

2. Get place predictions programmatically to create a customized user experience.

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:

. a query string containing the text typed by the user ( Required)

. an 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. ( Recommended)

. a RectangularBounds object, which specifies latitude and longitude bounds to constrain results to the specified region ( Recommended)

. an optional two-letter country code and a TypeFilter , which you can use to restrict the results to the specified place type.

Let’s add an EditText that would hold the text or query string from the user, a Button that would trigger the autocomplete search feature and a text area that would display the result. The resulting XML layout is as follows:

My approach here is that, once a user enters a search text in the EditText field, and clicks the button, the Places autocomplete search feature is triggered and the result is returned to the UI text area.

Note that the search result may be more than one.

Источник

Overview

Introduction

The Places SDK for Android allows you to build location-aware apps that respond contextually to the local businesses and other places near the user’s device. This means you can build rich apps based on places that mean something to the user, to complement the straightforward geographic-based services offered by the Android location services.

Concepts

The following interfaces provide the primary entry points to the Places SDK for Android:

  • Places provides programmatic access to Google’s database of local place and business information, as well as the device’s current place.
  • Autocomplete provides pre-made widgets to return place predictions in response to user search queries.

A place is defined as a physical space that has a name. Another way of thinking about a place is that it’s anything you can find on a map. Examples include local businesses, points of interest, and geographic locations. In the API, a place is represented by the Place interface. It includes information such as the name of the place and its address, geographical location, place ID, phone number, place type, website URL, and more.

API overview

Help your customers explore where they are and what’s around them:

  • Place Autocomplete automatically fills in the name and/or address of a place as users type.
  • Current Place returns a list of places where the user’s device is last known to be located along with an indication of the relative likelihood for each place.
  • Place Details return and display more detailed information about a place.
  • Place Photos returns high-quality images of a place.
  • Place IDs stores the unique ID for one or more places for retrieval of place information on demand.

Note: Google gathers anonymous usage statistics.

Policies and Terms

All applications that use the Places SDK for Android must adhere to the requirements described in the Google Maps Platform Terms of Service, Usage and Billing, and Displaying Attributions.

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.

Источник

Google Places Autocomplete Android Example

Google places autocomplete search input can be easily implemented using Google API. Google Places API allows you to query for place information on a variety of categories, such as cities, shops, and more. A Place Search returns a list of places along with more detailed information about each place.

Читайте также:  Бизнес карты для андроид

The new version of places SDK for Android is available now. The old version of the API which was part of Google Play Services is deprecated. In addition to extra features, the new places-SDK for android supports all the features which were supported by the old version except the Place Picker feature which is deprecated.

In this post, I am going to explain, How to display google places in autocomplete view with an example.

Checkout my other post using Google APIs,

Lets getting started to create application with places autocomplete in android.

First, In order to use Google Places API, you need to configure an API key in the Google developers console of your account.

1.Go to Google developers console and log in to your Google account.

2.Create New Project.

3.Go to the credential tab and create new credential .

4.Press edit credential, Then you can able to see your API KEY. Copy your API Key. (Optional)Then Select Android App in the Key Restriction. Then generate Keystore in your android studio and paste it into the package.

5. Finally, Go to Library, and enable the API Places API service.

Now the Google API Key setup Done.

Let’s get started with the coding part of the google places autocomplete example.

Create New Project in Android Studio.

Add the Places Library dependency to your apps build.gradle file

Copy the API key from the google console and add it to your strings.xml folder like this:

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.

In the activity within which you want to implement the autocomplete search feature, you’d need to initialize PlacesClient like this:

Next, initialize the AutocompleteSupportFragment and set the fields to specify which types of place data to return in the activity or fragment.

You can set type filter, to get the results of specified place type only, by calling the setTypeFilter method on the request object and passing one of the TypeFilter to it, for example, TypeFilter.CITIES. To know all the place types, see Place Type Filter documentation.

Also, You can set which are the place fields should be returned back as a response using setPlaceFields like Place. Field ID and Place.Field NAME etc. To know all the place fields, see Place.Field documentation

Finally, Add the listener for the autocomplete item selected on the google places list.

How to get the Places Photos in Places autocomplete

To get place photos, first you need to get photo metadata by calling findCurrentPlace or fetchPlace API and passing Place.Field.PHOTO_METADATAS in those requests. Each place contains a list of photos, so you will get a list of PhotoMetadata objects for each place.

After getting PhotoMetadata objects, pick one object, create FetchPhotoRequest object and pass it to fetchPhoto() API call to get a photo.

That’s on google places autocomplete.

You can download the example in Github.

Conclusion

Thanks for reading. Please try to create an example yourself and let me know your feedback in the comments.

Источник

Place Autocomplete

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:

  • Add an autocomplete widget to save development time and ensure a consistent user experience.
  • Get place predictions programmatically to create a customized user experience.

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

  • By default, the fragment has no border or background. To provide a consistent visual appearance, nest the fragment within another layout element such as a CardView.
  • If you are using the Autocomplete fragment, and need to override onActivityResult , you must call super.onActivityResult , otherwise the fragment will not function properly.

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

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 Autocomplete.IntentBuilder to create an intent, passing the desired Autocomplete mode. The intent must call startActivityForResult , passing in a request code that identifies the intent.
  2. Override the onActivityResult callback to receive the selected place.

Create an autocomplete intent

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

Kotlin

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:

Override the onActivityResult callback

To receive a notification when the 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.

Kotlin

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:

  • Required: A query string containing the text typed by the user.
  • Recommended: A 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.
  • Recommended: A RectangularBounds object, which specifies latitude and longitude bounds to constrain results to the specified region.
  • Optional: One or more two-letter country codes (ISO 3166-1 Alpha-2), indicating the country or countries to which results should be restricted.

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.

Kotlin

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.

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.

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:

  • To prefer results within the defined region, call setLocationBias() (some results from outside the defined region may still be returned).
  • To only show results within the defined region, call setLocationRestriction() (only results within the defined region will be returned).
  • To return only results that conform to a particular place type, call setTypeFilter() (for example, specifying TypeFilter.ADDRESS will return only results with a precise address).
  • To return only results within up to five specified countries, call setCountries() . Countries must be passed as a two-character, ISO 3166-1 Alpha-2 compatible country code.

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

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

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 type

You can restrict results from an autocomplete request so they only return a certain place type. If the results aren’t restricted, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the GEOCODE and ESTABLISHMENT types; however, this has the same effect as specifying no types.

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

The following code example shows calling setTypeFilter() on an AutocompleteSupportFragment to set a filter returning only results with a precise address.

Kotlin

The following code example shows calling setTypeFilter() on an IntentBuilder to set a filter returning only results with a precise address.

Kotlin

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

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

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:

  • Rate limit is 100 requests per second (QPS). It is calculated as the sum of client-side and server-side requests for all applications using the credentials of the same project.

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.

Place Autocomplete optimization

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

Here are some general guidelines:

  • The quickest way to develop a working user interface is to use the Maps JavaScript API Autocomplete widget, Places SDK for Android Autocomplete widget, or Places SDK for iOS Autocomplete UI control
  • Develop an understanding of essential Place Autocomplete data fields from the start.
  • Location biasing and location restriction fields are optional but can have a significant impact on autocomplete performance.
  • Use error handling to make sure your app degrades gracefully if the API returns an error.
  • Make sure your app handles when there is no selection and offers users a way to continue.

Cost optimization best practices

Basic cost optimization

To optimize the cost of using the Place Autocomplete service, use field masks in Place Details and Place Autocomplete widgets to return only the place data fields you need.

Advanced cost optimization

Consider programmatic implementation of Place Autocomplete in order to access Per Request pricing and request Geocoding API results about the selected place instead of Place Details. 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:

  • If you only need the latitude/longitude or address of the user’s selected place, the Geocoding API delivers this information for less than a Place Details call.
  • If users select an autocomplete prediction within an average of four Autocomplete predictions requests or fewer, Per Request pricing may be more cost-effective than Per Session pricing.

For help selecting the Place Autocomplete 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 with Place Details.
Since your application requires Place Details such as the place name, business status, or opening hours, your implementation of Place Autocomplete should use a session token (programmatically or built into the JavaScript, Android, or iOS widgets) for a total cost of $0.017 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 requests and the Place Details 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 requests. When requesting Place Details about the selected prediction, include the following parameters:

  1. The place ID from the Place Autocomplete response
  2. The session token used in the Place Autocomplete 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 for your application, depending on the performance of your Place Autocomplete usage. Every application’s Autocomplete 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 prediction in your application.

Do your users select a Place Autocomplete prediction in four or fewer requests, on average?

Implement Place Autocomplete programmatically without session tokens and call Geocoding API on the selected place prediction.
Geocoding API delivers addresses and latitude/longitude coordinates for $0.005 per request. Making four Place Autocomplete — Per Request requests costs $0.01132 so the total cost of four requests plus a Geocoding API call about the selected place prediction would be $0.01632 which is less than the Per Session Autocomplete price of $0.017 per session. 1

Consider employing performance best practices to help your users get the prediction they’re looking for in even fewer characters.

Use session-based Place Autocomplete with Place Details.
Since the average number of requests you expect to make before a user selects a Place Autocomplete prediction exceeds the cost of Per Session pricing, your implementation of Place Autocomplete should use a session token for both the Place Autocomplete requests and the associated Place Details request for a total cost of $0.017 per session. 1

Widget implementation
Session management is automatically built into the JavaScript, Android, or iOS widgets. This includes both the Place Autocomplete requests and the Place Details 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 requests. When requesting Place Details about the selected prediction, include the following parameters:

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

Consider delaying Place Autocomplete requests
You can employ strategies such as delaying a Place Autocomplete 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 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 $0.01632 (4 * $0.00283 Autocomplete Per Request + $0.005 Geocoding). 1

If delaying requests can get your average programmatic request below four, you can follow the guidance for performant Place Autocomplete 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.

Costs listed here are in USD. Please refer to the Google Maps Platform Billing page for full pricing information.

Performance best practices

The following guidelines describe ways to optimize Place Autocomplete performance:

  • Add country restrictions, location biasing, and (for programmatic implementations) language preference to your Place Autocomplete implementation. Language preference is not needed with widgets since they pick language preferences from the user’s browser or mobile device.
  • If Place Autocomplete is accompanied by a map, you can bias location by map viewport.
  • In situations when a user does not choose one of the Autocomplete predictions, generally because none of those predictions are the desired result-address, you can re-use the original user input to attempt to get more relevant results:
    • If you expect the user to enter only address information, re-use the original user input in a call to the Geocoding API.
    • If you expect the user to enter queries for a specific place by name or address, use a Find Place request. If results are only expected in a specific region, use location biasing.

    Other scenarios when it’s best to fall back to the Geocoding API include:

    • Users inputting subpremise addresses in countries other than Australia, New Zealand, or Canada. For example, the US address «123 Bowdoin St #456, Boston MA, USA» is not supported by Autocomplete. (Autocomplete supports subpremise addresses only in Australia, New Zealand, and Canada. Supported address formats in these three countries include «9/321 Pitt Street, Sydney, New South Wales, Australia» or «14/19 Langana Avenue, Browns Bay, Auckland, New Zealand» or «145-112 Renfrew Dr, Markham, Ontario, Canada».)
    • Users inputting addresses with road-segment prefixes like «23-30 29th St, Queens» in New York City or «47-380 Kamehameha Hwy, Kaneohe» on the island of Kauai in Hawai’i.

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.

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.

Источник

Читайте также:  Загрузить уровень для андроида
Оцените статью