Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to Implement Current Location Button Feature in Google Maps in Android?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 device

Follow 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 ‘’

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.


    <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 version="1.0" encoding="utf-8"?>
    <fragment xmlns:android=""
        android:name="" />

Step 6: Working with MainActivity.kt (back-end)

What we did in short is:

  1. Fetched the API key that we stored in Step 2.
  2. Initialized the Places API with the use of the API key.
  3. Initialized the Map fragment in the layout (activity_main.xml).
  4. Initialized fused location client.
  5. Initialized Button in the layout (activity_main.xml).
  6. Created a function to get the last location.
  7. Created a function to request a new location.
  8. Created a function for location callback.
  9. Created a function to check if the GPS of the device is turned on.
  10. Created a function to check if permissions for accessing the location are granted.
  11. Created a function to grant requests to permissions for accessing the location.
  12. 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.


import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
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?) {
        // Fetching API_KEY which we wrapped
        val ai: ApplicationInfo = applicationContext.packageManager
            .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA)
        val value = ai.metaData[""]
        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( as SupportMapFragment
        // Initializing fused location client
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        // Adding functionality to the button
        val btn = findViewById<Button>(
        btn.setOnClickListener {
    // Services such as getLastLocation()
      // will only run once map is ready
    override fun onMapReady(p0: GoogleMap) {
        mMap = p0
    // Get current location
    private fun getLastLocation() {
        if (checkPermissions()) {
            if (isLocationEnabled()) {
                mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
                    val location: Location? = task.result
                    if (location == null) {
                    } else {
                        currentLocation = LatLng(location.latitude, location.longitude)
                        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)
        } else {
    // Get current location, if shifted
      // from previous location
    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)
            mLocationRequest, mLocationCallback,
    // 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(
    // 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() {
            arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
    // 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)) {


Note: The application will prompt for permission requests, kindly allow once. Also, keep the device connected to the internet.

My Personal Notes arrow_drop_up
Last Updated : 23 May, 2021
Like Article
Save Article
Similar Reads