Getting current location (Latitude, Longitude, Country) in Android - Android Studio

Getting current location (Latitude, Longitude, Country) in Android – Android Studio

Getting user’s current location like latitude, longitude, city, country in Android is big and important task for all android developers to create an app related to location.

In this tutorial, we will discuss how to get these location informations using GPS/Network Provider.

The Kotlin version of this tutorial can be found Here

 

Current location in Android – Android Studio

Download project files of Android Current Location app with all custom images & font.

Steps to Get current location  (Latitude, Longitude, Country) in Android – Android Studio


1. Create a new project in Android Studio in a normal way.

2. Open your AndroidManifest.xml file and add internet connect permission and location permission. Your manifest file will look like this-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androstock.currentlocation">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

3. Open your activity_main.xml file. We are going to add simply a Button and a TextView.

<?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"
    android:background="#3F51B5">



    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/locationText"
        android:text=""
        android:textColor="#FFFFFF"
        android:textSize="17sp"
        android:textAlignment="center"
        android:layout_centerInParent="true"
        android:layout_above="@+id/getLocationBtn"
        android:layout_marginBottom="10dp"
        android:padding="10dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Current Location"
        android:layout_centerInParent="true"
        android:background="#FFFFFF"
        android:padding="10dp"
        android:id="@+id/getLocationBtn"/>


</RelativeLayout>

Finally we are heading towards the Java coding.

4. We are going to make the activity fullscreen. So add the following line before your setContentView().

getSupportActionBar().hide();

As higher versions of Android need in app permission so we will request in app permission this way-

if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

       ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);

}

LocationManager class provides the facility to get latitude and longitude coordinates of current location. The class in which you want to get location should implement LocationListener and override all its abstract methods.

Finally your MainActivity.java will look like-

package com.androstock.currentlocation;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements LocationListener {

    Button getLocationBtn;
    TextView locationText;

    LocationManager locationManager;

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

        getLocationBtn = (Button)findViewById(R.id.getLocationBtn);
        locationText = (TextView)findViewById(R.id.locationText);


        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);

        }


        getLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocation();
            }
        });
    }

    void getLocation() {
        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
        }
        catch(SecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        locationText.setText("Latitude: " + location.getLatitude() + "\n Longitude: " + location.getLongitude());

        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            locationText.setText(locationText.getText() + "\n"+addresses.get(0).getAddressLine(0)+", "+
                            addresses.get(0).getAddressLine(1)+", "+addresses.get(0).getAddressLine(2));
        }catch(Exception e)
        {

        }

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(MainActivity.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }
}

 

21 Comments

  • intania (#)
    July 7th, 2017

    I try your toturials about get location and build weather app and your tutorial always work, thank you very much 🙂

  • Rahul (#)
    July 24th, 2017

    Error in textview
    locationText = (TextView)findViewById(R.id.locationtext);

    id.locationtext <- this location is in red colour

  • Nikolay (#)
    July 31st, 2017

    Hello, I wanted to ask how to make the weather app with GPS Location please tell here or on my e-mail. Thanks a lot!

  • Tricia (#)
    August 20th, 2017

    Hello can u show me tutorial how to merge the weather app and the gps location pls

  • AiswaryaRaj (#)
    August 22nd, 2017

    Hai i’m a beginner in Android studio.I had a project to create a weather app, I want know how to get weather details while searching for a particular location using API .

  • shubhs (#)
    February 9th, 2018

    awesome….thnk you so muchhhhhhhhhhhhhh

  • Barud (#)
    February 14th, 2018

    Hi,
    Thanks for the tutorial. Can you please create a tutorial to get the map of the current location in a fragment?

  • rakesh (#)
    February 14th, 2018

    problem solved

  • Angel (#)
    March 3rd, 2018

    Thank you.
    It works great.
    Easy to follow code.

    Thank you very much.

  • meha (#)
    March 28th, 2018

    thnk you your code is very useful for me

  • Just (#)
    April 2nd, 2018

    really good .. It’s works. Thank you so much. 🙂

  • Naveena (#)
    May 31st, 2018

    Hey!!Thanks a lot …Your code just helped me .

  • Roni Skinner (#)
    June 25th, 2018

    My project will not let me use @Override method. When I make it private and get rid of the @Override call the app crashes before it gives me the coordinates. What should I do?

  • Abbas Khan Adrali (#)
    July 22nd, 2018

    thankyou so much made my day!!!

  • Nikhil Bhasin (#)
    August 4th, 2018

    The Location thing works fine on Emulator but not on android phone.

  • Narcisse (#)
    September 12th, 2018

    Great job, it work for me

Leave a comment

Your email address will not be published. Required fields are marked *