How to Implement Google’s Places AutocompleteBar in Android?
If you ever used Google Maps on mobile or accessed from a desktop, you must have definitely typed in some location into the search bar and selected one of its results. The result might have had fields such as an address, phone numbers, ratings, timings, etc. Moreover, if you ever searched for a place on google.com from a desktop, you must have got many search results along with a place card with the aforementioned parameters aligned from the right. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Both the applications implement a single API, which publicly is known as the Places API. Autocomplete bar is a feature of Places API, that recommends a list of locations based on the words typed by the user in the search bar. With the help of Places API, we will implement the AutocompleteBar and fetch information of the location.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Get and hide the API key
Our application utilizes Google’s Places API to implement the Autocomplete Bar, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs. Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?.
Step 3: Adding the dependency in the build.gradle file
We need to import libraries that support the implementation of our Autocomplete Bar. As Autocomplete Bar is a feature of Places API, we need to append its latest dependency in the build.gradle file. The below is the dependency which must be added.
implementation ‘com.google.android.libraries.places:places:2.4.0’
Step 4: Add internet permission in your Manifest file
Navigate to the app > manifest folder and write down the following permissions to it.
<!–Internet permission and network access permission–>
<uses-permission android:name=”android.permission.INTERNET”/>
Step 5: Implementing Autocomplete Bar fragment in the activity_main.xml file (front-end)
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > < LinearLayout android:id = "@+id/ll1" android:layout_width = "match_parent" android:layout_height = "40sp" android:layout_marginLeft = "10sp" android:layout_marginRight = "10sp" android:background = "@android:color/white" > < fragment android:id = "@+id/autocomplete_fragment1" android:name = "com.google.android.libraries.places.widget.AutocompleteSupportFragment" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </ LinearLayout > < TextView android:id = "@+id/tv1" android:layout_below = "@id/ll1" android:layout_marginTop = "20sp" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_centerInParent = "true" /> </ RelativeLayout > |
Step 6: Working with MainActivity.kt (back-end)
What we did in short is:
- Fetched the API key that we stored in Step 2.
- Initialized the Places API with the use of the API key.
- Initialized the Autocomplete fragment in the layout (activity_main.xml).
- Declared the location parameters which we wish to get from the API.
- Declared on select listener event, which posts the parameters in the text view in the layout when the location is clicked from the autocomplete bar results.
onError function is a member function of the select listener, which will throw a toast message “Some error occurred” in the event of failure. A general cause could be the unavailability of the internet. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package org.w3wiki.myapplication import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import android.widget.Toast import com.google.android.gms.common.api.Status import com.google.android.libraries.places.api.Places import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.widget.AutocompleteSupportFragment import com.google.android.libraries.places.widget.listener.PlaceSelectionListener class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Fetching API_KEY which we wrapped val ai: ApplicationInfo = applicationContext.packageManager .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData[ "api_key" ] val apiKey = value.toString() // Initializing the Places API // with the help of our API_KEY if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } // Initialize Autocomplete Fragments // from the main activity layout file val autocompleteSupportFragment1 = supportFragmentManager.findFragmentById(R.id.autocomplete_fragment1) as AutocompleteSupportFragment? // Information that we wish to fetch after typing // the location and clicking on one of the options autocompleteSupportFragment1!!.setPlaceFields( listOf( Place.Field.NAME, Place.Field.ADDRESS, Place.Field.PHONE_NUMBER, Place.Field.LAT_LNG, Place.Field.OPENING_HOURS, Place.Field.RATING, Place.Field.USER_RATINGS_TOTAL ) ) // Display the fetched information after clicking on one of the options autocompleteSupportFragment1.setOnPlaceSelectedListener(object : PlaceSelectionListener { override fun onPlaceSelected(place: Place) { // Text view where we will // append the information that we fetch val textView = findViewById<TextView>(R.id.tv1) // Information about the place val name = place.name val address = place.address val phone = place.phoneNumber.toString() val latlng = place.latLng val latitude = latlng?.latitude val longitude = latlng?.longitude val isOpenStatus : String = if (place.isOpen == true ){ "Open" } else { "Closed" } val rating = place.rating val userRatings = place.userRatingsTotal textView.text = "Name: $name \nAddress: $address \nPhone Number: $phone \n" + "Latitude, Longitude: $latitude , $longitude \nIs open: $isOpenStatus \n" + "Rating: $rating \nUser ratings: $userRatings" } override fun onError(status: Status) { Toast.makeText(applicationContext, "Some error occurred" , Toast.LENGTH_SHORT).show() } }) } } |
Output:
Note: Turn the Internet (Wifi/Mobile Data) on before launching the application.