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
How to Implement Current Location Button Feature in Google Maps in Android?
The current location is a feature on Google Maps, that helps us locate the device's position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going t
5 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI fl
4 min read
How to Implement Country Code Picker in Android?
Country Code Picker (CCP) is an android library that helps users to select country codes (country phone codes) for telephonic forms. CCP provided a UI component that helps the user to select country codes, country flags, and many more in an android spinner. It gives well-designed looks to forms on t
3 min read
How to Implement Date Range Picker in Android?
Date Range Picker is a widely used feature in many popular Android apps and an essential component of Material Design. It allows users to select a range of dates such as a start and end date for various purposes including scheduling, filtering data, and setting time boundaries. Some Of The Real Life
4 min read
How to Implement Custom Searchable Spinner in Android?
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the c
5 min read
Android Jetpack Compose: How to Use Google Maps
Many applications such as Swiggy, Zomato, Ola, and others use Google Maps within their application to display the location within their application. Most of these applications use Google Maps to display the details within their application. In this article, we will take a look at How to integrate Go
4 min read
How to Create Google Lens Application in Android?
We have seen the new Google Lens application in which we can capture images of any product and from that image, we can get to see the search results of that product which we will display inside our application. What are we going to build in this article? We will be building a simple application in w
10 min read
How to Create Google Glass Options Menu in Android?
Google Glass is a wearable device developed by Google that allows users to perform various tasks such as taking photos, recording videos, and sending messages. In this article, we will show you how to create a Google Glass options menu in Android. Step By Step Implementation Step 1: To create a new
2 min read
How to Implement Item Click Interface in Android?
When we click on an item in an application either it gives some information or it redirects the user to any other page. In this article, we will learn that how we can implement Item Click Interface in an android application. What we are going to build in this article?In this article, we will be usin
5 min read
How to Implement Android SearchView with Example
The SearchView widget is used to provide a search interface to the user so that the user can enter his search query and submit a request to the search provider and get a list of query suggestions or results.Class Syntax:public class SearchView extends LinearLayout implements CollapsibleActionViewCla
4 min read