Android
Location Services
Latitude and Longitude
GPS
Mobile Development

How to get Latitude and Longitude of the mobile device in android?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Using Location Services in Android to Obtain Latitude and Longitude

Accessing the latitude and longitude of a mobile device in Android applications is a common requirement and can be achieved using the Location Services provided by Android. This article will delve into the methods, permissions, handling, accuracy, and best practices for obtaining a mobile device’s geolocation.

Understanding Location Services in Android

Android provides APIs through Google Play Services and the Android location package (android.location) to access geographical locations. Two commonly used components are:

  1. LocationManager: Part of the Android framework, which provides location updates through different providers.
  2. FusedLocationProviderClient: Part of Google Play Services, which simplifies the API for obtaining location and improves accuracy and battery efficiency.

Key Components

  • LocationManager: An older API; can use GPS, network, or passive providers.
  • FusedLocationProviderClient: More efficient and preferred; automatically chooses the best provider.

Permissions

Android requires certain permissions for accessing location:

xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  • ACCESS_FINE_LOCATION: For GPS and high accuracy.
  • ACCESS_COARSE_LOCATION: For network-based locations.

From Android 6.0 (API level 23), location permissions are considered "dangerous" and require runtime permissions handling.

Implementing Location Access Using FusedLocationProviderClient

Below is a step-by-step guide on how to implement geolocation access using the FusedLocationProviderClient.

Step 1: Add Google Play Services to Your Project

First, ensure you have Google Play Services in your build.gradle file:

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

Step 2: Request Permissions at Runtime

Ensure your app has runtime permissions handling; here's an example:

java
1if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
2    != PackageManager.PERMISSION_GRANTED) {
3    ActivityCompat.requestPermissions(this, new String[]{
4        Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
5}

Step 3: Initialize FusedLocationProviderClient and Request Location

java
1FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
2
3// Check permission again before proceeding
4if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
5    == PackageManager.PERMISSION_GRANTED) {
6    fusedLocationClient.getLastLocation()
7        .addOnSuccessListener(this, new OnSuccessListener<Location>() {
8            @Override
9            public void onSuccess(Location location) {
10                // Got last known location, in some rare situations this can be null.
11                if (location != null) {
12                    double latitude = location.getLatitude();
13                    double longitude = location.getLongitude();
14
15                    // Do something with latitude and longitude
16                }
17            }
18        });
19}

Handling Null Location

The getLastLocation() method provides a quick, cached location. In cases where the location is null, you may need to request a current location update:

java
1LocationRequest locationRequest = LocationRequest.create()
2        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
3        .setInterval(10 * 1000)        // 10 seconds
4        .setFastestInterval(2000);     // 2 seconds
5
6LocationCallback locationCallback = new LocationCallback() {
7    @Override
8    public void onLocationResult(LocationResult locationResult) {
9        if (locationResult == null) {
10            return;
11        }
12        for (Location location : locationResult.getLocations()) {
13            double latitude = location.getLatitude();
14            double longitude = location.getLongitude();
15
16            // Do something with latitude and longitude
17        }
18    }
19};
20
21fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());

Best Practices for Background Location Requests

  • Adhere to Android background location access policies, especially since API level 29 (Android 10).
  • Consider battery consumption; high precision locations drain battery faster.
  • Make sure to unsubscribe from location updates when they're no longer needed to release resources.

Common Issues and Solutions

IssueSolution
Null location from getLastLocation()Use requestLocationUpdates() for a fresh update.
App crashing on location accessEnsure permissions are handled at runtime and check permission before accessing.
High battery consumptionUse lower priority location requests when high accuracy is not required.

Conclusion

Accessing a device's latitude and longitude is straightforward with Android Location Services. Using the FusedLocationProviderClient is typically recommended due to its efficient handling of resources and improved accuracy. Ensure all permissions are correctly handled, and always optimize for battery usage especially when working with background location updates.

By understanding and implementing these elements, you can effectively integrate location-based features into your Android applications.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.