Sunday, July 25, 2021

How to Get Address From Current Location In Android

Learn about Android Get Current Address Location From Latitude Longitude in this tutorial.

Learn how to get location name from latitude and longitude in android.

In this tutorial, we will get current country, state, city, postal or pin code, zip code and location name from latitude and longitude.

For this purpose, we will use Geocoder and Address classes from android library.

Step 1. Manifest Permissions

Write down the below lines in AndroidManifest.xml file.

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

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

Step 2. Some Dependencies

In your build.gradle(Module : app) file, add the following two lines

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

 implementation 'com.karumi:dexter:5.0.0'

Step 4. Main Java Class

Following is the source code for the MainActivity.java class.

import android.Manifest;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.location.Address;

import android.location.Geocoder;

import android.location.Location;

import android.location.LocationManager;

import android.net.Uri;

import android.provider.Settings;

import android.support.v4.app.ActivityCompat;

import android.support.v7.app.AlertDialog;

import android.support.v7.app.AppCompatActivity;

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.common.ConnectionResult;

import com.google.android.gms.common.api.GoogleApiClient;

import com.google.android.gms.location.LocationRequest;

import com.google.android.gms.location.LocationServices;

import com.karumi.dexter.Dexter;

import com.karumi.dexter.MultiplePermissionsReport;

import com.karumi.dexter.PermissionToken;

import com.karumi.dexter.listener.DexterError;

import com.karumi.dexter.listener.PermissionRequest;

import com.karumi.dexter.listener.PermissionRequestErrorListener;

import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.IOException;

import java.util.List;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private static final String TAG = "MainActivity";

    private GoogleApiClient mGoogleApiClient;

    private Location mLocation;

  //  private LocationManager mLocationManager;

    private LocationRequest mLocationRequest;

    private com.google.android.gms.location.LocationListener listener;

    private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */

    private long FASTEST_INTERVAL = 2000; /* 2 sec */

    private LocationManager locationManager;

    private Double latitude = 0.00;

    private Double longitude = 0.00;

    private TextView textView, tvCountry, tvCity, tvState, tvPincode, tvFeature;

    private Button btn;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        requestMultiplePermissions();

        mGoogleApiClient = new GoogleApiClient.Builder(this)

                .addConnectionCallbacks(this)

                .addOnConnectionFailedListener(this)

                .addApi(LocationServices.API)

                .build();

      //  mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

        checkLocation();

        textView = findViewById(R.id.tv);

        tvCountry = findViewById(R.id.tvCountry);

        tvState = findViewById(R.id.tvState);

        tvCity = findViewById(R.id.tvCity);

        tvPincode = findViewById(R.id.tvPincode);

        tvFeature = findViewById(R.id.tvFeature);

        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                setAddress(latitude,longitude);

            }

        });

    }

    @Override

    public void onConnected(Bundle bundle) {

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

            // TODO: Consider calling

            //    ActivityCompat#requestPermissions

            // here to request the missing permissions, and then overriding

            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,

            //                                          int[] grantResults)

            // to handle the case where the user grants the permission. See the documentation

            // for ActivityCompat#requestPermissions for more details.

            return;

        }

        startLocationUpdates();

        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if(mLocation == null){

            startLocationUpdates();

        }

        if (mLocation != null) {

            // mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));

            //mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));

        } else {

            Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();

        }

    }

    @Override

    public void onConnectionSuspended(int i) {

        Log.i(TAG, "Connection Suspended");

        mGoogleApiClient.connect();

    }

    @Override

    public void onConnectionFailed(ConnectionResult connectionResult) {

        Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());

    }

    @Override

    protected void onStart() {

        super.onStart();

        if (mGoogleApiClient != null) {

            mGoogleApiClient.connect();

        }

    }

    @Override

    protected void onStop() {

        super.onStop();

        if (mGoogleApiClient.isConnected()) {

            mGoogleApiClient.disconnect();

        }

    }

    protected void startLocationUpdates() {

        // Create the location request

        mLocationRequest = LocationRequest.create()

                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)

                .setInterval(UPDATE_INTERVAL)

                .setFastestInterval(FASTEST_INTERVAL);

        // Request location updates

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

            // TODO: Consider calling

            //    ActivityCompat#requestPermissions

            // here to request the missing permissions, and then overriding

            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,

            //                                          int[] grantResults)

            // to handle the case where the user grants the permission. See the documentation

            // for ActivityCompat#requestPermissions for more details.

            return;

        }

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,

                mLocationRequest, this);

        Log.d("reque", "--->>>>");

    }

    @Override

    public void onLocationChanged(Location location) {

        String msg = "Updated Location: " +

                Double.toString(location.getLatitude()) + "," +

                Double.toString(location.getLongitude());

        latitude = location.getLatitude();

        longitude = location.getLongitude();

        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

    private boolean checkLocation() {

        if(!isLocationEnabled())

            showAlert();

        return isLocationEnabled();

    }

    private void showAlert() {

        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        dialog.setTitle("Enable Location")

                .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +

                        "use this app")

                .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                        startActivity(myIntent);

                    }

                })

                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    }

                });

        dialog.show();

    }

    private boolean isLocationEnabled() {

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||

                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    }

    private void  requestMultiplePermissions(){

        Dexter.withActivity(this)

                .withPermissions(

                        Manifest.permission.ACCESS_COARSE_LOCATION,

                        Manifest.permission.ACCESS_FINE_LOCATION)

                .withListener(new MultiplePermissionsListener() {

                    @Override

                    public void onPermissionsChecked(MultiplePermissionsReport report) {

                        // check if all permissions are granted

                        if (report.areAllPermissionsGranted()) {

                            Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();

                            //startLocationUpdates();

                        }

                        // check for permanent denial of any permission

                        if (report.isAnyPermissionPermanentlyDenied()) {

                            // show alert dialog navigating to Settings

                            openSettingsDialog();

                        }

                    }

                    @Override

                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {

                        token.continuePermissionRequest();

                    }

                }).

                withErrorListener(new PermissionRequestErrorListener() {

                    @Override

                    public void onError(DexterError error) {

                        Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();

                    }

                })

                .onSameThread()

                .check();

    }

    private void openSettingsDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("Required Permissions");

        builder.setMessage("This app require permission to use awesome feature. Grant them in app settings.");

        builder.setPositiveButton("Take Me To SETTINGS", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

                Uri uri = Uri.fromParts("package", getPackageName(), null);

                intent.setData(uri);

                startActivityForResult(intent, 101);

            }

        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

            }

        });

        builder.show();

    }

    private void setAddress(Double latitude, Double longitude){

        Geocoder geocoder;

        List<Address> addresses = null;

        geocoder = new Geocoder(this, Locale.getDefault());

        try {

            addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

        } catch (IOException e) {

            e.printStackTrace();

        }

        if(addresses.size() > 0) {

            Log.d("max", " " + addresses.get(0).getMaxAddressLineIndex());

            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()

            String city = addresses.get(0).getLocality();

            String state = addresses.get(0).getAdminArea();

            String country = addresses.get(0).getCountryName();

            String postalCode = addresses.get(0).getPostalCode();

            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

            addresses.get(0).getAdminArea();

            textView.setText(address);

            tvFeature.setText(knownName);

            tvCountry.setText(country);

            tvState.setText(state);

            tvCity.setText(city);

            tvPincode.setText(postalCode);

        }

    }

}

Checking the Code

Let us see how the source code of Main Activity will work.

First of all, consider the following lines

private static final String TAG = "MainActivity";

    private GoogleApiClient mGoogleApiClient;

    private Location mLocation;

  //  private LocationManager mLocationManager;

    private LocationRequest mLocationRequest;

    private com.google.android.gms.location.LocationListener listener;

    private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */

    private long FASTEST_INTERVAL = 2000; /* 2 sec */

    private LocationManager locationManager;

    private Double latitude = 0.00;

    private Double longitude = 0.00;

    private TextView textView, tvCountry, tvCity, tvState, tvPincode, tvFeature;

    private Button btn;

With this code, compiler will define objects of various useful classes.

Classes like GoogleApiClient, Location, LocationManager, LocationRequest etc. will help us to get the current latitude and longitude.

Then there are objects of text view and button widgets.

Two double variables latitude and longitude will hold the co ordinates.

Now read the code of the onCreate() method.

First of all, compiler will call requestMultiplePermissions() method.

Code for requestMultiplePermissions() method is as the below

private void  requestMultiplePermissions(){

        Dexter.withActivity(this)

                .withPermissions(

                        Manifest.permission.ACCESS_COARSE_LOCATION,

                        Manifest.permission.ACCESS_FINE_LOCATION)

                .withListener(new MultiplePermissionsListener() {

                    @Override

                    public void onPermissionsChecked(MultiplePermissionsReport report) {

                        // check if all permissions are granted

                        if (report.areAllPermissionsGranted()) {

                            Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();

                            //startLocationUpdates();

                        }

                        // check for permanent denial of any permission

                        if (report.isAnyPermissionPermanentlyDenied()) {

                            // show alert dialog navigating to Settings

                            openSettingsDialog();

                        }

                    }

                    @Override

                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {

                        token.continuePermissionRequest();

                    }

                }).

                withErrorListener(new PermissionRequestErrorListener() {

                    @Override

                    public void onError(DexterError error) {

                        Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();

                    }

                })

                .onSameThread()

                .check();

    }

As you can see that we are asking for ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in this method.

If the user have given all the permissions then compiler will show a toast like “All permissions are granted!”

Otherwise, it will call the openSettingDialog() method.

source code for openSettingDialog() method is as the following

private void openSettingsDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("Required Permissions");

        builder.setMessage("This app require permission to use awesome feature. Grant them in app settings.");

        builder.setPositiveButton("Take Me To SETTINGS", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

                Uri uri = Uri.fromParts("package", getPackageName(), null);

                intent.setData(uri);

                startActivityForResult(intent, 101);

            }

        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

            }

        });

        builder.show();

    }

Compiler will show one alert dialog to the user.

It has two buttons. One is Cancel and another is “Take me to settings.”

when the user will call “Take me to settings.” button, compiler will open the app settings, from where user can turn on the permissions.

Now again see the onCreate() method.

After requestMultiplePermissions() method, compiler will call checkLocation() method.

This method will check whether the location service of android device is on or off.

If it is off then, compiler will pop up one alert dialog and will tell user to turn on the location service.

Now some overriden methods are there. For example, onConnected(), onConnectionSuspendend(), onConnectionFailed(), onStart(), onStop() and onLocationChanged().

All these methods are related to getting current location.

Compiler will call onLocationChanged() method every 2 seconds. This method will give us updated latitude and longitudes.

Source code for onLocationChanged() method is as the following

@Override

    public void onLocationChanged(Location location) {

        String msg = "Updated Location: " +

                Double.toString(location.getLatitude()) + "," +

                Double.toString(location.getLongitude());

        latitude = location.getLatitude();

        longitude = location.getLongitude();

        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

Compiler will store latitude and longitude in global variables.

When the user will click the button, compiler will call setAddress() method.

setAddress() method will get two parameters. One latitude and another will longitude.

We will pass global variables as these parameter, so this method will always get updated current co ordinates.

Code structure for setAddress() method is as the below

private void setAddress(Double latitude, Double longitude){

        Geocoder geocoder;

        List<Address> addresses = null;

        geocoder = new Geocoder(this, Locale.getDefault());

        try {

            addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

        } catch (IOException e) {

            e.printStackTrace();

        }

        if(addresses.size() > 0) {

            Log.d("max", " " + addresses.get(0).getMaxAddressLineIndex());

            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()

            String city = addresses.get(0).getLocality();

            String state = addresses.get(0).getAdminArea();

            String country = addresses.get(0).getCountryName();

            String postalCode = addresses.get(0).getPostalCode();

            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

            addresses.get(0).getAdminArea();

            textView.setText(address);

            tvFeature.setText(knownName);

            tvCountry.setText(country);

            tvState.setText(state);

            tvCity.setText(city);

            tvPincode.setText(postalCode);

        }

    }

In this method, compiler will first create the object of Geocoder class.

Then it will create a list with the objects of Address class.

.getFromLocation() method will give us the address associated with the latitude and longitude.

Result given by .getFromLocation() method will give us full address, city, country, state, pin code and finally we will set these information in various text views.

1 comment:


  1. Thanks for this information. it is helpfull and worthy
    Laptop Repair Center offers quality service for your laptop at a reasonable cost. We offer doorstep support, 24*7 onsite support, repair all brand laptops, have an expert team for onsite support, and much more. for more contact us on 7291903784
    laptop repair center in Delhi

    ReplyDelete