Getting Current Location on Android Using Kotlin

Have you ever wonder how to get a current location on Android programmatically? Hmm, the answer is so easy. You need to know how to use the fused location provider. Basically, it will give you the last known location which can be used as the current location.

What will the app look like?

The app will look like this after you finish this tutorial:

Getting Current Location on Android

What will you learn?

  • Know how to use the FusedLocationProviderClient to access the last location data.
  • Opening the Google Maps app using the current location data.

Note: In this post, I used Android Studio 4.0, make sure you use the latest Android Studio, or if you already install it, be sure to check the latest update. The Kotlin version that I used is Kotlin 1.3.72.

Getting Started – Getting Current Location on Android 

Open your Android Studio and choose to Start a new Android Studio Project. Then set the Application Name CurrentLocationApp and select Kotlin as the language. Give the Activity Name MainActivity and wait until the Android Studio finishes preparing your project.

First, set up the app/build.gradle file and add this inside the dependencies block code:

implementation 'com.google.android.gms:play-services-location:17.0.0'

After that, sync the project and proceed to the next step.

Preparing the XML Layout

The first is preparing the XML layout for our app here. Open the activity_main.xml inside the res/layout directory and put the code below:

<?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">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical"
       android:padding="30dp">

       <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:textAppearance="@style/TextAppearance.AppCompat.Title"
           android:text="Current Location:"
           />

       <TextView
           android:id="@+id/tvLatitude"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:textAppearance="@style/TextAppearance.AppCompat.Body1"
           android:layout_marginTop="20dp"
           android:text="Latitude: -"
           />

       <TextView
           android:id="@+id/tvLongitude"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:textAppearance="@style/TextAppearance.AppCompat.Body1"
           android:layout_marginTop="10dp"
           android:text="Longitude: -"
           />

       <TextView
           android:id="@+id/tvProvider"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:textAppearance="@style/TextAppearance.AppCompat.Body1"
           android:layout_marginTop="10dp"
           android:text="Provider: -"
           />

       <Button
           android:id="@+id/btOpenMap"
           android:layout_width="150dp"
           android:layout_height="wrap_content"
           android:background="@color/colorAccent"
           android:text="Open Map"
           android:textColor="@android:color/white"
           android:layout_marginTop="30dp"
           android:visibility="gone"
           />

   </LinearLayout>

   <Button
       android:id="@+id/btGetLocation"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@color/colorPrimary"
       android:layout_margin="30dp"
       android:text="Get Current Location"
       android:textColor="@android:color/white"
       android:layout_alignParentBottom="true"
       />

</RelativeLayout>

This layout only contains TextView to show latitude and longitude data and also Buttons to get the current location and open the Google map application. The app will look like this if you run the app:

Write some codes

Open the MainActivity.kt file and write this code:

package com.thesimplycoder.currentlocationapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

   private val LOCATION_PERMISSION_REQ_CODE = 1000;

   private lateinit var fusedLocationClient: FusedLocationProviderClient

   private var latitude: Double = 0.0
   private var longitude: Double = 0.0

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       // initialize fused location client
       fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
   }
}

First, we need to initialize the FusedLocationProviderClient in order to access the current location data on Android. Just write the code adobe and it is very easy.

Next, create a new method getCurrentLocation() that we will implement the getLastLocation() function.

private fun getCurrentLocation() {
   // checking location permission
   if (ActivityCompat.checkSelfPermission(this,
           Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

       // request permission
       ActivityCompat.requestPermissions(this,
           arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQ_CODE);

       return
   }

   fusedLocationClient.lastLocation
       .addOnSuccessListener { location ->
           // getting the last known or current location
           latitude = location.latitude
           longitude = location.longitude

           tvLatitude.text = "Latitude: ${location.latitude}"
           tvLongitude.text = "Longitude: ${location.longitude}"
           tvProvider.text = "Provider: ${location.provider}"

           btOpenMap.visibility = View.VISIBLE
       }
       .addOnFailureListener {
           Toast.makeText(this, "Failed on getting current location",
               Toast.LENGTH_SHORT).show()
       }
}

On Kotlin, you access the location data using the lastLocation provided by FusedLocationProviderClient and it will return the location data such as latitude, longitude, provider, etc. using the fused location provider requires you to grant the location permission. The permission that will be used is ACCESS_FINE_LOCATION.

Open the AndroidManifest.xml file and add the permission:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

After that, back to MainActivity.kt file and add another method onRequestPermissionsResult() to handle permission callback and the openMap() method to implement the open on Google Map app.

override fun onRequestPermissionsResult(
   requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
   when (requestCode) {
       LOCATION_PERMISSION_REQ_CODE -> {
           if (grantResults.isNotEmpty() &&
               grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // permission granted
           } else {
               // permission denied
               Toast.makeText(this, "You need to grant permission to access location",
                   Toast.LENGTH_SHORT).show()
           }
       }
   }
}

private fun openMap() {
   val uri = Uri.parse("geo:${latitude},${longitude}")
   val mapIntent = Intent(Intent.ACTION_VIEW, uri)
   mapIntent.setPackage("com.google.android.apps.maps")
   startActivity(mapIntent)
}

Try to run the app and it will look like this:

Don’t forget to allow the permission request to get the current location.

The final code of the MainActivity.kt will be like this:

package com.thesimplycoder.currentlocationapp

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

   private val LOCATION_PERMISSION_REQ_CODE = 1000;

   private lateinit var fusedLocationClient: FusedLocationProviderClient

   private var latitude: Double = 0.0
   private var longitude: Double = 0.0

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       // initialize fused location client
       fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

       btGetLocation.setOnClickListener {
           getCurrentLocation()
       }

       btOpenMap.setOnClickListener {
           openMap()
       }
   }

   private fun getCurrentLocation() {
       // checking location permission
       if (ActivityCompat.checkSelfPermission(this,
               Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

           // request permission
           ActivityCompat.requestPermissions(this,
               arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQ_CODE);

           return
       }

       fusedLocationClient.lastLocation
           .addOnSuccessListener { location ->
               // getting the last known or current location
               latitude = location.latitude
               longitude = location.longitude

               tvLatitude.text = "Latitude: ${location.latitude}"
               tvLongitude.text = "Longitude: ${location.longitude}"
               tvProvider.text = "Provider: ${location.provider}"

               btOpenMap.visibility = View.VISIBLE
           }
           .addOnFailureListener {
               Toast.makeText(this, "Failed on getting current location",
                   Toast.LENGTH_SHORT).show()
           }
   }

   override fun onRequestPermissionsResult(
       requestCode: Int, permissions: Array<out String>, grantResults: IntArray
   ) {
       when (requestCode) {
           LOCATION_PERMISSION_REQ_CODE -> {
               if (grantResults.isNotEmpty() &&
                   grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   // permission granted
               } else {
                   // permission denied
                   Toast.makeText(this, "You need to grant permission to access location",
                       Toast.LENGTH_SHORT).show()
               }
           }
       }
   }

   private fun openMap() {
       val uri = Uri.parse("geo:${latitude},${longitude}")
       val mapIntent = Intent(Intent.ACTION_VIEW, uri)
       mapIntent.setPackage("com.google.android.apps.maps")
       startActivity(mapIntent)
   }
}

Where to go next?

You can download this full code from the link below:

Download the final code

Be sure to check my other cool posts here about:

I hope you like my post, comment, and share it with love!

You may also like...

2 Responses

  1. Arihant Jain says:

    Thanks

  1. January 3, 2022

    […] Getting Current Location on Android Using Kotlin […]

Join the discussion...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: