If you work on an application that requires your users to fill out their addresses, there is an SDK that you should consider using. It is the Google's Place Autocomplete SDK. It enables your users to select a place from the prediction list, instead of typing everything by themselves. It must enhance your app's user experience.
In this post, I will show you how to integrate the SDK in your Android app using Hilt and Jetpack Compose. The full codebase can be found on my Github repository.
Install dependencies
In your project build.gradle add listed plugins.
Also, modify your app-level build file (apps/build.gradle).
Set Google Maps API Key
Open your local.properties and set a key:
And set the key as meta-data in a manifest (src/main/AndroidManifest.xml).
Moreover, update your apps/build.gradle to load the API key and set it to BuildConfig. Later you will need to retrieve it to instantiate the Places SDK.
Initialize Places SDK
Places SDK needs to be initialized before being accessed. You can do it in onCreate() of your application class.
Instantiate Places Client and provides it
Create a Hilt module to provide PlacesClient. It requires an Android Context so it needs to be installed into SingletonComponent.
Create a View Model and communicate with Places SDK
First, let's create models that represent UI states.
Then we can use those models inside a View Model. The AutocompleteSessionToken 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. The detail is here.
Create Screen
Finally, we build a simple UI where you can fill out an address and show predictions.
That's all. Here is a screencast showing how it works. I tried it somewhere in Berlin, Germany, because it's where I live but the SDK works worldwide.
The Places SDK is very powerful and I believe it improves your app's UX in many cases. So, unsurprisingly, it's not for free. Calling findAutocompletePredictions() costs a fee per session until you call fetchPlace() (within a few minutes of the beginning of the querying).