Paramclasses Academy - Blog

Tutorials Details

←
Post 30 of 40
→

How to setup Android Location and Maps Integration ?

How to setup Android Location and Maps Integration ?

November 4, 2026

Introduction

Location-based features are an important part of modern Android applications. Apps use location services to show the user's current position, display nearby places, provide navigation, and track selected locations.

Android provides location APIs through Google Play services. The Google Maps SDK for Android allows developers to display interactive maps, add markers, and move the map camera to a selected location.

In this tutorial, we will learn how to integrate location services and Google Maps into an Android application using Java.

By the end of this tutorial, you will build a Current Location Map App that can:

  • Request location permission from the user.

  • Retrieve the device's current latitude and longitude.

  • Display the coordinates on the screen.

  • Show Google Maps inside the application.

  • Add a marker at the user's current location.

  • Move the map camera to the current location.

1. What Is Location-Based App Development?

Location-based app development means creating applications that use a device's geographical position to provide useful features.

For example:

  • Navigation applications use location to provide directions.

  • Food delivery applications use location to identify delivery addresses.

  • Travel applications show nearby hotels and tourist attractions.

  • Fitness applications use location to track walking and running routes.

  • Shopping applications can display nearby stores.

A geographical location is commonly represented using two values:

Latitude: Represents the north-south position of a location.

Longitude: Represents the east-west position of a location.

For example:

double latitude = 21.2514;
double longitude = 81.6296;

These are example coordinates, not a live device location.

2. Understanding Android Location Services

Android devices can determine their location using different sources.

GPS

GPS stands for Global Positioning System. It uses satellite signals to estimate the device's geographical position.

GPS can provide accurate location information, especially outdoors, but it may consume more battery power and can be less reliable indoors.

Wi-Fi and Mobile Networks

Android can also use nearby Wi-Fi networks and mobile network information to estimate a device's location.

This can be useful when GPS signals are weak or unavailable.

Fused Location Provider

The Fused Location Provider combines available location sources, such as GPS, Wi-Fi, and mobile networks, to provide location information.

It is available through Google Play services and is commonly used in Android applications.

We will use FusedLocationProviderClient in this tutorial.

3. What Is Google Maps SDK for Android?

Google Maps SDK for Android allows developers to display and customize Google Maps inside Android applications.

With this SDK, you can:

  • Display interactive Google Maps.

  • Add location markers.

  • Change map camera position.

  • Zoom in and zoom out.

  • Display information windows.

  • Enable map controls.

  • Show the user's current location when permission is available.

We will use SupportMapFragment to display the map and GoogleMap to control its features.

4. Create a New Android Studio Project

First, open Android Studio.

Follow these steps:

  1. Click New Project.

  2. Select Empty Views Activity.

  3. Enter the project name: CurrentLocationMapApp.

  4. Select Java as the programming language.

  5. Choose the minimum SDK supported by your development environment.

  6. Click Finish.

Wait for Gradle Sync to complete.

We will use the following files:

  • MainActivity.java

  • activity_main.xml

  • AndroidManifest.xml

  • Module-level build.gradle

5. Add Google Maps and Location Dependencies

Open the module-level build.gradle file.

Add these dependencies inside the dependencies block:

implementation 'com.google.android.gms:play-services-maps:20.1.0'
implementation 'com.google.android.gms:play-services-location:21.4.0'

These dependencies provide:

  • play-services-maps: Google Maps integration.

  • play-services-location: Fused Location Provider and location APIs.

Click Sync Now and wait for the project to synchronize.

If your project uses Kotlin DSL, add the dependencies in this format:

implementation("com.google.android.gms:play-services-maps:20.1.0")
implementation("com.google.android.gms:play-services-location:21.4.0")

6. Create a Google Maps API Key

Google Maps SDK requires an API key to display maps in your application.

Follow these steps:

  1. Open the Google Cloud Console.

  2. Create a new Google Cloud project or select an existing project.

  3. Enable Maps SDK for Android.

  4. Open the Credentials section.

  5. Create an API key.

  6. Configure the key for your Android application.

For production applications, restrict the API key by specifying the Android package name, SHA-1 certificate fingerprint, and the APIs that the key is allowed to use.

Do not publish an unrestricted API key or commit secret key files to a public Git repository.

Configure the API Key

For this tutorial, use the Android Secrets Gradle Plugin approach.

In the top-level build.gradle file, add the plugin declaration inside the existing plugins block:

id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' version '2.0.1' apply false

In the app-level build.gradle file, apply the plugin:

plugins {
    id 'com.android.application'
    id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
}

Keep any other plugins already required by your project.

Create a file named secrets.properties in the project root:

MAPS_API_KEY=YOUR_API_KEY

Replace YOUR_API_KEY with your actual Google Maps API key.

Create or update local.defaults.properties in the project root:

MAPS_API_KEY=DEFAULT_API_KEY

The default value is only a fallback. Do not put a real production key in this file.

Make sure secrets.properties is excluded from version control.

7. Add Location Permissions

To access the device's location, Android requires location permissions.

Open AndroidManifest.xml and add these permissions above the application element:

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

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

The permissions have different purposes:

  • ACCESS_COARSE_LOCATION provides approximate location.

  • ACCESS_FINE_LOCATION allows the application to request precise location.

On Android 12 and later, the user can grant approximate location even when the application requests both permissions.

We will request both permissions together so the application can handle either choice.

For this foreground location example, we do not need ACCESS_BACKGROUND_LOCATION.

8. Configure the Google Maps API Key in AndroidManifest.xml

Inside the application element of AndroidManifest.xml, add the Maps API key metadata:

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}" />

This tells the Maps SDK which API key to use.

Your manifest should contain the permissions and metadata in the correct locations. Do not place the meta-data element outside the application element.

9. Design the Application Layout

Now create the user interface.

Open activity_main.xml and replace its content with:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="12dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Current Location Map"
        android:textSize="22sp"
        android:textStyle="bold"
        android:gravity="center"
        android:padding="10dp" />

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

    <TextView
        android:id="@+id/txtLocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Location: Not available"
        android:textSize="16sp"
        android:padding="10dp" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

Understanding the XML Components

TextView: Displays the application title and location coordinates.

Button: Allows the user to request their current location.

FragmentContainerView: Hosts the Google Maps fragment.

The layout_weight property allows the map to use the remaining screen space.

10. Implement Location and Google Maps in Java

Open MainActivity.java.

Replace its content with the following code.

package com.example.currentlocationmapapp;

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 android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.Priority;
import com.google.android.gms.location.CurrentLocationRequest;
import com.google.android.gms.tasks.CancellationTokenSource;

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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    private Button btnGetLocation;
    private TextView txtLocation;

    private FusedLocationProviderClient fusedLocationClient;
    private GoogleMap googleMap;
    private Marker currentMarker;

    private final ActivityResultLauncher<String[]> locationPermissionLauncher =
            registerForActivityResult(
                    new ActivityResultContracts.RequestMultiplePermissions(),
                    result -> {
                        boolean fineGranted = Boolean.TRUE.equals(
                                result.get(Manifest.permission.ACCESS_FINE_LOCATION));

                        boolean coarseGranted = Boolean.TRUE.equals(
                                result.get(Manifest.permission.ACCESS_COARSE_LOCATION));

                        if (fineGranted || coarseGranted) {
                            getCurrentLocation();
                        } else {
                            Toast.makeText(
                                    this,
                                    "Location permission was denied",
                                    Toast.LENGTH_SHORT
                            ).show();
                        }
                    }
            );

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

        btnGetLocation = findViewById(R.id.btnGetLocation);
        txtLocation = findViewById(R.id.txtLocation);

        fusedLocationClient =
                LocationServices.getFusedLocationProviderClient(this);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map);

        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }

        btnGetLocation.setOnClickListener(v -> checkLocationPermission());
    }

    @Override
    public void onMapReady(@NonNull GoogleMap map) {
        googleMap = map;

        googleMap.getUiSettings().setZoomControlsEnabled(true);

        updateMapLocationLayer();
    }

    private void checkLocationPermission() {

        boolean fineGranted = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED;

        boolean coarseGranted = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED;

        if (fineGranted || coarseGranted) {
            getCurrentLocation();
        } else {
            locationPermissionLauncher.launch(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            });
        }
    }

    private void updateMapLocationLayer() {

        if (googleMap == null) {
            return;
        }

        boolean fineGranted = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED;

        boolean coarseGranted = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED;

        try {
            if (fineGranted || coarseGranted) {
                googleMap.setMyLocationEnabled(true);
            } else {
                googleMap.setMyLocationEnabled(false);
            }
        } catch (SecurityException e) {
            Toast.makeText(
                    this,
                    "Location permission is required",
                    Toast.LENGTH_SHORT
            ).show();
        }
    }

    private void getCurrentLocation() {

        boolean fineGranted = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED;

        boolean coarseGranted = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED;

        if (!fineGranted && !coarseGranted) {
            checkLocationPermission();
            return;
        }

        updateMapLocationLayer();

        CancellationTokenSource cancellationTokenSource =
                new CancellationTokenSource();

        CurrentLocationRequest locationRequest =
                new CurrentLocationRequest.Builder()
                        .setPriority(Priority.PRIORITY_BALANCED_POWER_ACCURACY)
                        .build();

        fusedLocationClient.getCurrentLocation(
                locationRequest,
                cancellationTokenSource.getToken()
        ).addOnSuccessListener(location -> {

            if (location != null) {
                showLocationOnScreen(location);
            } else {
                txtLocation.setText(
                        "Unable to get location. Please try again."
                );
            }

        }).addOnFailureListener(e -> {

            txtLocation.setText(
                    "Location error: " + e.getMessage()
            );

        });
    }

    private void showLocationOnScreen(Location location) {

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        txtLocation.setText(
                "Latitude: " + latitude +
                "\nLongitude: " + longitude
        );

        LatLng currentLatLng = new LatLng(latitude, longitude);

        if (googleMap != null) {

            if (currentMarker != null) {
                currentMarker.remove();
            }

            currentMarker = googleMap.addMarker(
                    new MarkerOptions()
                            .position(currentLatLng)
                            .title("My Current Location")
            );

            googleMap.animateCamera(
                    CameraUpdateFactory.newLatLngZoom(
                            currentLatLng,
                            16f
                    )
            );
        }
    }
}

Important: Replace the package declaration at the top with the actual package name of your Android project.

11. Understand the Important Java Methods

FusedLocationProviderClient

fusedLocationClient =
        LocationServices.getFusedLocationProviderClient(this);

This creates the client used to request location information from Google Play services.

Runtime Permission Request

locationPermissionLauncher.launch(new String[]{
    Manifest.permission.ACCESS_FINE_LOCATION,
    Manifest.permission.ACCESS_COARSE_LOCATION
});

This requests both precise and approximate location permissions.

The user can choose approximate location on supported Android versions. Your app must work even when only approximate permission is granted.

Get Current Location

fusedLocationClient.getCurrentLocation(
    locationRequest,
    cancellationTokenSource.getToken()
);

This requests a current location using the selected priority.

We use PRIORITY_BALANCED_POWER_ACCURACY to balance location accuracy and battery consumption.

The returned location can be null, so the application checks for a valid result before using it.

Get Latitude and Longitude

double latitude = location.getLatitude();
double longitude = location.getLongitude();

These methods return the geographical coordinates of the location result.

Add a Marker

googleMap.addMarker(
    new MarkerOptions()
        .position(currentLatLng)
        .title("My Current Location")
);

This adds a marker to the map at the specified coordinates.

Move the Map Camera

googleMap.animateCamera(
    CameraUpdateFactory.newLatLngZoom(currentLatLng, 16f)
);

This smoothly moves the map camera to the current location and sets the zoom level.

12. Run and Test the Application

Now run your application on an Android device or an emulator that includes Google Play services.

Follow these steps:

  1. Open the application.

  2. Wait for the Google Map to load.

  3. Tap Get Current Location.

  4. Android displays the location permission dialog.

  5. Select an appropriate permission option.

  6. The app requests the current location.

  7. Latitude and longitude appear on the screen.

  8. A marker appears on the map.

  9. The map camera moves to the returned location.

If you use an emulator, configure its simulated location through the emulator's Extended Controls.

13. Common Errors and Their Solutions

Error 1: Google Map Is Not Displaying

Possible reasons:

  • API key is incorrect.

  • Maps SDK for Android is not enabled.

  • API key restrictions are incorrect.

  • The emulator does not include Google Play services.

  • Billing configuration is incomplete.

Solution: Check the Google Cloud project, API key configuration, Logcat messages, and emulator system image.

Error 2: Location Permission Denied

Possible reason: The user has denied location access.

Solution: Explain why location access is required and allow the user to enable permission through Android settings when necessary.

Error 3: Location Is Returning Null

Possible reasons:

  • Device location is disabled.

  • The emulator has no simulated location.

  • Location information is temporarily unavailable.

  • The device has limited network or GPS access.

Solution: Enable device location, check the emulator's location settings, and try again.

Error 4: Map Shows but Marker Is Missing

Possible reasons:

  • The location request has not completed.

  • The location result is null.

  • The map is not ready when the location result arrives.

Solution: Check the location result and ensure that the map is available before adding a marker. If necessary, keep the latest location and display it after onMapReady().

14. Important Location Security and Privacy Practices

Location information is sensitive user data. Android developers should follow these practices:

  • Request location permission only when the feature needs it.

  • Explain why the application needs location access.

  • Support approximate location when precise location is not essential.

  • Do not collect location information without user awareness.

  • Avoid unnecessary background location access.

  • Protect location data when sending it to a server.

  • Use HTTPS for network communication.

  • Restrict Google Maps API keys to the required Android application and APIs.

For this tutorial, we only request foreground location access while the application is being used.

15. What Is the Difference Between Location and Google Maps?

Location services and Google Maps work together, but they are not the same thing.

Location Services determine the device's geographical coordinates.

Google Maps SDK displays a map and lets the application show those coordinates visually.

For example, FusedLocationProviderClient retrieves the location, while GoogleMap displays the marker at that location.

Conclusion

In this tutorial, we learned how to integrate Android location services and Google Maps using Java.

We covered location providers, latitude and longitude, runtime permissions, FusedLocationProviderClient, Google Maps SDK, map fragments, markers, and camera movement.

We also created a practical Current Location Map App that retrieves the user's location and displays it on a Google Map.

These concepts are useful for developing navigation applications, delivery applications, travel apps, tracking systems, and other location-based Android applications.

Frequently Asked Questions

1. What is Fused Location Provider in Android?

Fused Location Provider is a Google Play services API that combines different location sources to provide location information efficiently.

2. What is the difference between ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION?

ACCESS_FINE_LOCATION allows an application to request precise location, while ACCESS_COARSE_LOCATION provides approximate location.

3. What is Google Maps SDK for Android?

Google Maps SDK for Android allows developers to integrate interactive Google Maps into Android applications.

4. What is a latitude and longitude?

Latitude and longitude are geographical coordinates used to identify a location on Earth.

5. Do we need an API key for Google Maps?

Yes. The Maps SDK for Android requires an API key configured through a Google Cloud project.

6. Can we use Google Maps in Java-based Android applications?

Yes. Google Maps SDK for Android supports Java and Kotlin development.

←
Post 30 of 40
→