Open In App

How to Get Current Location in Android?

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user's current location in Android. There are two ways to get the current location of any Android device:

  • Android’s Location Manager API
  • Fused Location Provider: Google Play Services Location APIs

Question: Which one is efficient and why?
Answer: Fused Location Provider because it optimizes the device’s use of battery power.

Before moving any of the above methods we will have to take location permission.

Step by Step Implementation

Step 1: Create a new project

To create a new project in the Android Studio, please refer to How to Create/Start a New Project in Android Studio?


Step 2: Adding permissions in manifest

Navigate to app > manifests > AndroidManifest.xml and add the following permissions under the <manifest/> tag.

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

In order to receive location updates from NETWORK_PROVIDER or GPS_PROVIDER, you must request the user’s permission by declaring either the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission, respectively, in your Android manifest file. Without these permissions, your application will fail at runtime when requesting location updates.

If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. Permission for ACCESS_COARSE_LOCATION allows access only to NETWORK_PROVIDER.


Step 3: Working with activity_main.xml

Navigate to app > res > layout > activity_main.xml and add a textview to display location and a button to fetch the location.

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/locationText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Location will be shown here"
        android:textSize="18sp"
        android:textAlignment="center"
        android:padding="16dp" />

    <Button
        android:id="@+id/getLocationBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Current Location" />

</LinearLayout>


Design UI:

get-current-location-main


Step 4: Working with MainActivity file

Navigate to app > java > {package-name} > MainActivity.java/.kt and add the following code.

MainActivity.java
package org.geeksforgeeks.demo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
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 com.google.android.gms.tasks.OnSuccessListener;

public class MainActivity extends AppCompatActivity {

    // Declare variables
    private FusedLocationProviderClient locationClient;
    private TextView locationText;
    private static final int LOCATION_PERMISSION_REQUEST = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize TextView and Button from layout
        locationText = findViewById(R.id.locationText);
        Button getLocationBtn = findViewById(R.id.getLocationBtn);

        // Initialize the location provider client
        locationClient = LocationServices.getFusedLocationProviderClient(this);

        // Set a click listener for the button
        getLocationBtn.setOnClickListener(v -> getCurrentLocation());
    }

    // Function to get the current location
    private void getCurrentLocation() {
        // Check if location permission is granted
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Request permission if not granted
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST);
            return;
        }

        // Fetch the last known location
        locationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    // Get latitude and longitude
                    double lat = location.getLatitude();
                    double lon = location.getLongitude();
                    
                    // Display location in TextView
                    locationText.setText("Latitude: " + lat + "\nLongitude: " + lon);
                } else {
                    // Display error message if location is null
                    locationText.setText("Unable to get location");
                }
            }
        });
    }

    // Handle the result of the permission request
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == LOCATION_PERMISSION_REQUEST && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // If permission is granted, fetch location
            getCurrentLocation();
        } else {
            // If permission is denied, show message
            locationText.setText("Location permission denied");
        }
    }
}
MainActivity.kt
package org.geeksforgeeks.demo

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices

class MainActivity : AppCompatActivity() {

    // Declare a variable for the FusedLocationProviderClient
    private lateinit var locationClient: FusedLocationProviderClient

    // Declare a TextView to display location data
    private lateinit var locationText: TextView

    // Define a constant for the location permission request code
    private val LOCATION_PERMISSION_REQUEST = 1001

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

        // Initialize the TextView and Button from the layout
        locationText = findViewById(R.id.locationText)
        val getLocationBtn = findViewById<Button>(R.id.getLocationBtn)

        // Initialize the location provider client
        locationClient = LocationServices.getFusedLocationProviderClient(this)

        // Set a click listener for the button to get the current location
        getLocationBtn.setOnClickListener {
            getCurrentLocation()
        }
    }

    // Function to get the current location
    private fun getCurrentLocation() {
        // Check if the location permission is granted
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // If permission is not granted, request it from the user
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                LOCATION_PERMISSION_REQUEST
            )
            return
        }

        // Fetch the last known location
        locationClient.lastLocation.addOnSuccessListener { location ->
            if (location != null) {
                // If location is available, extract latitude and longitude
                val lat = location.latitude
                val lon = location.longitude

                // Display location in the TextView
                locationText.text = "Latitude: $lat\nLongitude: $lon"
            } else {
                // If location is null, display an error message
                locationText.text = "Unable to get location"
            }
        }
    }

    // Handle the result of the permission request
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        // Check if the permission was granted
        if (requestCode == LOCATION_PERMISSION_REQUEST &&
            grantResults.isNotEmpty() &&
            grantResults[0] == PackageManager.PERMISSION_GRANTED
        ) {
            // If permission is granted, fetch the location
            getCurrentLocation()
        } else {
            // If permission is denied, update the TextView with an error message
            locationText.text = "Location permission denied"
        }
    }
}

Refer to the following github repo to get the entire code: Getting-Current-Location-Android


Output:



Next Article

Similar Reads