How to Implement Current Location Button Feature in Google Maps in Android?
Last Updated :
23 May, 2021
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 to implement this project using the Kotlin language.
Screenshot of the actual Google Map App on Android deviceFollow the below steps to implement a map and a button to navigate to the device's current position
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 Google Map, 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 dependencies in the build.gradle file
We need to add the below dependency for importing libraries to support the implementation of the Google Map.
implementation 'com.google.android.libraries.places:places:2.4.0'
Step 4: Adding permissions to the application in the Manifest.xml file
As the application majorly deals with the current location, we give the application the permissions to access the location. To give the application such permissions, declare permissions between the manifest and application opening tags in the following way.
XML
<manifest...>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application ...>
Step 5: Implementing a simple Button & Google Map 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<Button
android:id="@+id/currentLoc"
android:layout_width="30sp"
android:layout_height="40sp"
android:layout_alignBottom="@id/map"
android:layout_alignEnd="@id/map"
android:layout_alignRight="@id/map"
android:layout_marginRight="30sp"
android:layout_marginBottom="30sp"
/>
</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 Map fragment in the layout (activity_main.xml).
- Initialized fused location client.
- Initialized Button in the layout (activity_main.xml).
- Created a function to get the last location.
- Created a function to request a new location.
- Created a function for location callback.
- Created a function to check if the GPS of the device is turned on.
- Created a function to check if permissions for accessing the location are granted.
- Created a function to grant requests to permissions for accessing the location.
- Created a function to call getLastLocation() when permissions are granted.
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.libraries.places.api.Places
class MainActivity : AppCompatActivity(), OnMapReadyCallback {
private val pERMISSION_ID = 42
lateinit var mFusedLocationClient: FusedLocationProviderClient
lateinit var mMap: GoogleMap
// Current location is set to India, this will be of no use
var currentLocation: LatLng = LatLng(20.5, 78.9)
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["com.google.android.geo.API_KEY"]
val apiKey = value.toString()
// Initializing the Places API with the help of our API_KEY
if (!Places.isInitialized()) {
Places.initialize(applicationContext, apiKey)
}
// Initializing Map
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
// Initializing fused location client
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
// Adding functionality to the button
val btn = findViewById<Button>(R.id.currentLoc)
btn.setOnClickListener {
getLastLocation()
}
}
// Services such as getLastLocation()
// will only run once map is ready
override fun onMapReady(p0: GoogleMap) {
mMap = p0
getLastLocation()
}
// Get current location
@SuppressLint("MissingPermission")
private fun getLastLocation() {
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
val location: Location? = task.result
if (location == null) {
requestNewLocationData()
} else {
currentLocation = LatLng(location.latitude, location.longitude)
mMap.clear()
mMap.addMarker(MarkerOptions().position(currentLocation))
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 16F))
}
}
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
} else {
requestPermissions()
}
}
// Get current location, if shifted
// from previous location
@SuppressLint("MissingPermission")
private fun requestNewLocationData() {
val mLocationRequest = LocationRequest()
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
mLocationRequest.interval = 0
mLocationRequest.fastestInterval = 0
mLocationRequest.numUpdates = 1
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
mFusedLocationClient.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
)
}
// If current location could not be located, use last location
private val mLocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val mLastLocation: Location = locationResult.lastLocation
currentLocation = LatLng(mLastLocation.latitude, mLastLocation.longitude)
}
}
// function to check if GPS is on
private fun isLocationEnabled(): Boolean {
val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
)
}
// Check if location permissions are
// granted to the application
private fun checkPermissions(): Boolean {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
) {
return true
}
return false
}
// Request permissions if not granted before
private fun requestPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
pERMISSION_ID
)
}
// What must happen when permission is granted
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == pERMISSION_ID) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
getLastLocation()
}
}
}
}
Output:
Note: The application will prompt for permission requests, kindly allow once. Also, keep the device connected to the internet.
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
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
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
Android RecyclerView in Kotlin In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
4 min read
ProgressBar in Android Progress Bar are used as loading indicators in android applications. These are generally used when the application is loading the data from the server or database. There are different types of progress bars used within the android application as loading indicators. In this article, we will take a lo
3 min read
Kotlin Array An Array is one of the most fundamental data structures in practically all programming languages. The idea behind an array is to store multiple items of the same data type, such as an integer or string, under a single variable name. Arrays are used to organize data in programming so that a related s
6 min read