How to Get User Location in Android with Location Services

Β·

7 min read

Introduction

Hello there! If you're eager to incorporate user location into your Android project, you've come to the right place. This page is your comprehensive guide to everything about location services. I'll walk you through each step, making the integration process a breeze and empowering your app with accurate user location. Let's jump right in and make your project truly location-savvy with 'How to Get User Location in Android with Location Services'

Get User Location in Android with Location Services

1. Permissions

In order to obtain the user's location, it is necessary to grant permission for accessing location information. The following code can be utilized to request and acquire the required user location permission, and make sure to add the following permission entry in the manifest file.

app->manifests->AndroidManifest.xml.

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

The first one asks for precise and accurate location details, perfect for apps like maps or navigation. The second one is for apps that don't need pinpoint accuracy and can work with a more general location estimate, saving battery and resources. By including both permissions, your app gains the flexibility to cater to different location needs, ensuring a seamless user experience.

2. Essential Dependency for Location Services

It's like getting a pre-built toolkit from Google that makes handling location stuff super easy. Without it, you'd have to do a lot more work to make your app understand and use location info.

app->build.gradel.kts (module file)

implementation("com.google.android.gms:play-services-location:17.0.0")

So, adding this line is like inviting a helpful friend (or superhero) to do all the heavy lifting for you and make sure your app smoothly knows where your users are.

3. Design Layout

Since our app is pretty chill, it's rocking a single star – the awesome MainActivity and its main layout. Picture this: a cool TextView shouting 'Current Location,' a button saying 'Get Location' (because why not?), and a bunch of friendly TextViews ready to spill the beans on latitude, longitude, address, city, and country. These details? Well, they're like secret messages from our MainActivity magic, and we're about to spill the deets in just a bit. Now, peek into the activity_main.xml file to see the cozy setup we've got going!

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:text="Current Location"
        android:textStyle="bold"
        android:textColor="@color/black"
        android:layout_marginTop="20dp"
        android:textSize="50dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lattitude"
        android:text="Lattitude"
        android:textSize="25dp"
        android:layout_marginTop="150dp"
        android:layout_marginStart="20dp"
        android:layout_marginBottom="20dp"
        android:textStyle="bold"
        android:textColor="@color/black"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/longitude"
        android:layout_alignStart="@id/lattitude"
        android:layout_below="@+id/lattitude"
        android:text="Longitude"
        android:textSize="25dp"
        android:layout_marginBottom="20dp"
        android:textStyle="bold"
        android:textColor="@color/black"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/address"
        android:layout_alignStart="@id/lattitude"
        android:layout_below="@+id/longitude"
        android:text="Address"
        android:textSize="25dp"
        android:layout_marginBottom="20dp"
        android:textStyle="bold"
        android:textColor="@color/black"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/city"
        android:layout_alignStart="@id/lattitude"
        android:layout_below="@+id/address"
        android:text="City"
        android:textSize="25dp"
        android:layout_marginBottom="20dp"
        android:textStyle="bold"
        android:textColor="@color/black"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/country"
        android:layout_alignStart="@id/lattitude"
        android:layout_below="@+id/city"
        android:text="Country"
        android:textSize="25dp"
        android:layout_marginBottom="10dp"
        android:textStyle="bold"
        android:textColor="@color/black"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:backgroundTint="@color/black"
        android:id="@+id/getLocation"
        android:text="Get Location"
        android:layout_marginTop="50dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/country"/>

</RelativeLayout>

4.Coding the Logic

Embark on an adventure into the heart of location services with our app's MainActivity code. This enchanting piece of code transforms your app into a location-savvy wizard, offering users a seamless experience. From fetching precise coordinates to crafting a user-friendly display of location details, this code serves as the backbone of our app's magic.

import android.Manifest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    FusedLocationProviderClient fusedLocationProviderClient;
    TextView latitude, longitude, address, city, country;
    Button getLocation;
    private final static int REQUEST_CODE = 100;

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

        // Initializing UI elements
        latitude = findViewById(R.id.latitude);
        longitude = findViewById(R.id.longitude);
        address = findViewById(R.id.address);
        city = findViewById(R.id.city);
        country = findViewById(R.id.country);
        getLocation = findViewById(R.id.getLocation);

        // Initializing FusedLocationProviderClient for location services
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        // Setting up click listener for the 'Get Location' button
        getLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLastLocation();
            }
        });
    }

    // Function to fetch the last known location
    private void getLastLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationProviderClient.getLastLocation()
                    .addOnSuccessListener(new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            if (location != null) {
                                // Log the latitude and longitude
                                Log.d("Location", "Latitude: " + location.getLatitude());
                                Log.d("Location", "Longitude: " + location.getLongitude());

                                // Use Geocoder to get detailed location information
                                try {
                                    Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
                                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

                                    // Display location details on UI elements
                                    latitude.setText("Latitude: " + addresses.get(0).getLatitude());
                                    longitude.setText("Longitude: " + addresses.get(0).getLongitude());
                                    address.setText("Address: " + addresses.get(0).getAddressLine(0));
                                    city.setText("City: " + addresses.get(0).getLocality());
                                    country.setText("Country: " + addresses.get(0).getCountryName());

                                    // Log detailed location information
                                    Log.d("Location", "Addresses: " + addresses.toString());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
        } else {
            // Request location permission if not granted
            askPermission();
        }
    }

    // Function to request location permission
    private void askPermission() {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
    }

    // Handle permission request result
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // If permission granted, fetch the last known location
                getLastLocation();
            } else {
                // If permission not granted, show a toast message
                Toast.makeText(MainActivity.this, "Please provide the required permission", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

In the code, think of FusedLocationProviderClient as the GPS manager, TextViews as digital signs showing location details, the 'Get Location' Button as the trigger to fetch the user's location, and REQUEST_CODE as a secret code for asking permission. Together, they make your app location-savvy! 🌐✨

5.Code Explanation

In the onCreate block of the MainActivity in this Android app, the scene is set for the app's debut. The method kicks off with the essential @Override annotation, indicating that it's customizing the behavior of the superclass. Following that, the super.onCreate(savedInstanceState) call ensures any necessary setup from the base class is executed. The subsequent setContentView(R.layout.activity_main) line pulls the curtain to reveal the layout defined in the activity_main.xml, marking the visual presentation of the app. The block then proceeds to link Java variables (latitude, longitude, address, city, country) to their counterparts in the XML layout, essentially establishing points of interaction with the screen. The fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) line is like the crew preparing the GPS system for action, a crucial step for fetching the user's location. Finally, the getLocation.setOnClickListener(new View.OnClickListener() { ... }) block orchestrates the 'Get Location' button, setting the stage for the main act where clicking the button triggers the getLastLocation function, initiating the process of obtaining and displaying the user's location. This block of code acts as the foundation, seamlessly blending the app's visual elements with the functionality that brings it to life. 🎭✨

The getLastLocation function checks if the app has the necessary location permission. If granted, it uses the fusedLocationProviderClient to fetch the last known location. The latitude, longitude, and address details are then displayed on the corresponding TextViews. If permission is lacking, the askPermission function is called, triggering a permission request.

The onRequestPermissionsResult method handles the user's response to the permission request. If granted, it invokes getLastLocation to fetch the location; otherwise, it displays a polite toast message asking for the required permission. Altogether, these methods ensure a smooth dance between permissions and location services, making the app a respectful guest on the user's device. πŸ•ΊπŸŒ

Output

The output gracefully retrieves and displays the user's location details, including latitude, longitude, address, city, and country, ensuring a seamless and user-friendly experience in the Android app.

Get User Location in Android with Location Services

Source Code

Explore the project's source code on GitHub! Delve into the details, understand how it works, and get hands-on with the code. The repository is your go-to place for transparency and collaboration

Github Source Code

Conclusion

To sum it up, incorporating location services into an Android app isn't just about codeβ€”it's about creating a smooth, user-friendly experience. From initial setup to handling permissions and displaying accurate location details, each step ensures an app that not only works seamlessly but also provides users with a delightful and precise location experience.

If you're a student gearing up for coding rounds and practice platforms, check out this insightful guide on the top 10 coding practice platforms for developers: Top 10 Coding Practice Platforms for Developers. And if you're on the lookout for hackathons, explore the possibilities in the coding revolution with this guide on the best hackathon platforms for 2023: 2023's Best Hackathon Platforms - Join the Coding Revolution. Happy coding! πŸš€

Don't hesitate to contact me if the code isn't functioning as expected or if you encounter any errors.

Did you find this article valuable?

Support vazidnh3's blog by becoming a sponsor. Any amount is appreciated!

Β