How to Implement Google's Places AutocompleteBar in Android?
Last Updated :
26 May, 2021
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.geeksforgeeks.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.
Similar Reads
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Kotlin Android Tutorial Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori
6 min read
Bottom Navigation Bar in Android We all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, WhatsApp, etc. In this article, let's learn how to implement such a functional Bottom Navigation Bar in the Android app. Why do we need a Bottom Navigation Bar? It allows the user to switch to di
6 min read
How to Change the Color of Status Bar in an Android App? A Status Bar in Android is an eye-catching part of the screen, all of the notification indications, battery life, time, connection strength, and plenty of things are shown here. An Android user may look at a status bar multiple times while using an Android application. It is a very essential part of
4 min read
Retrofit with Kotlin Coroutine in Android Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Introduction to Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, which has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 as a new language for the JVM. Kotlin is an object-oriented language, and a better lang
4 min read
Kotlin Data Types The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects.There are different data types
3 min read
Kotlin when expression In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to
6 min read
ToolBar in Android with Example In Android applications, Toolbar is a kind of ViewGroup that can be placed in the XML layouts of an activity. It was introduced by the Google Android team during the release of Android Lollipop(API 21). The Toolbar is basically the advanced successor of the ActionBar. It is much more flexible and cu
8 min read
Kotlin Constructor A constructor is a special member function that is automatically called when an object of a class is created. Its main purpose is to initialize properties or perform setup operations. In Kotlin, constructors are concise, expressive, and provide significant flexibility with features like default para
6 min read