How to get current location in android (latitude and longitude) with GPS is the today’s example.

Along with current location, we will also see how you can get address from current location and how to get latitude and longitude of any particular place or address.

1. Get Current Location In Android

It is necessary to find current location in android studio programmatically when you are developing location-based applications.

Globally, the location of any object is found in terms of the latitude and longitude.

For example, if you want to find restaurants near by you, you need your current gps location latitude and longitude.

With the help of latitude and longitude, you will be able to find location regardless of how far the object is from you.

In current GPS location android example tutorial, you will learn to get current latitude and longitude of Android device.

We will use Google’s FusedLocationAPI for getting current location with latitude and longitude.

Show the output of the tutorial in the below video.

Follow all the below steps carefully to get the current location.

Step 1. Create a new project in Android Studio.

Make a fresh new project in Android Studio. Make sure you have select Empty activity as a Main Activity while creating a new project.

Step 2. Update build.gradle(Module:app) file

Add below source code in build.gradle(Module:app)

compile 'com.google.android.gms:play-services:11.8.0'

We need to use google’s play services to accomplish our task of getting current latitude and longitude.

Above line will import all the necessary classes from google api.

Step 3. Implement necessary interfaces

These interfaces are required.

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

All the above interfaces are required for using google’s fusedlocation API.

We also need to override necessary methods associated with these interfaces.

Step 4. Declare instances:

Declare Necessary statements as per below source code.

private GoogleApiClient mGoogleApiClient; private Location mLocation; private LocationManager mLocationManager; private LocationRequest mLocationRequest;

All these instances will help to use location services of the android architecture.

Step 5. Put following in onCreate() method

Update your onCreate() method as per following:

mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview)); mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview)); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

Step 6. Last but not least, put required permissions in AndroidManifest.xml

Below two permissions are must to get desired results.

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

If you are targeting marshmallow and after versions (targetSdkVersion >=23) then you have to check for run-time permissions.

Now full source code:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.exampledemo.parsaniahardik.gpsdemocode"> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" 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>

build.gradle(Module:app)

apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.exampledemo.parsaniahardik.gpsdemocode" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.google.android.gms:play-services:9.0.2' }

activity_main.xml

<?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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/latitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Latitude:" android:textSize="18sp" /> <TextView android:id="@+id/latitude_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/latitude" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/latitude" android:textSize="16sp" /> <TextView android:id="@+id/longitude" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Longitude:" android:layout_marginTop="24dp" android:textSize="18sp" /> <TextView android:id="@+id/longitude_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/longitude" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/longitude" android:textSize="16sp"/> </RelativeLayout>

In the above layout file, I have used four TextViews. Two are static which will give you reference about which digit is latitude and which is other.

Other two textview represents the location factors and will be changed frequently.

After implementing interfaces, you need to override all of it’s required methods. Here is the full source code with those methods in MainActivity.java class.

Source snippet for the MainActivity.java file.

import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; 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.google.android.gms.maps.model.LatLng; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener { private static final String TAG = "MainActivity"; private TextView mLatitudeTextView; private TextView mLongitudeTextView; 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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview)); mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview)); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); checkLocation(); //check whether location service is enable or not in your phone } @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()); mLatitudeTextView.setText(String.valueOf(location.getLatitude())); mLongitudeTextView.setText(String.valueOf(location.getLongitude() )); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); // You can now create a LatLng Object for use with maps LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); } 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'.

Please 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); } }

Descriptions of the various methods

In above class, there is a method

checkLocation();

This method is used to check whether location service is on or off in your phone. If off, then it will pop up one dialog, which will take the user to settings to enable location service.

showAlert()

This method will prompt a dialog if the location settings of the device is off. Title of the dialog will tell user about this. From here, user can turn on the location or can simply ignore it.

startLocationUpdates()

In this method, android will finally use google’s FusedLocation API to fetch the current latitude and longitude of the android device.

onLocationChanged()

Latitude and Longitude are very sensitive factors. It changes constantly every seconds to fetch the exact gps location of the device.

When these two factors have changed their values, this method onLocationChanged() will be called every second.

I have updated the textview values which represents the latitude and longitude in this method.

We will get the values of latitude and longitude in the long variable format because we must consider 7 to 8 decimal digits for the accuracy of the gps location.

If you have any query or questions then use comment section to ask them.

I will be happy to solve your questions as quickly as possible.

2. 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

First of all, make a fresh new project in the android studio.

Select “Empty activity” as a main activity.

In order to fetch the current location, we need to have some permissions from the user.

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" />

We need to ask for runtime permissions in this case because location permission is sensitive in terms of user’s security and privacy.

We will ask it using dexter library in the main activity later.

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'

First line is for fetching the classes from google. These classes will help us to get the current location in terms of latitude and longitude of the user.

Second line is for dexter library which will help us to simplify the process of asking runtime location permissions.

Step 3. Main XML file

In your activity_main.xml file, add the following code snippet

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btn" android:text="fetch address"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Full Address : " android:textColor="#000" android:textSize="18sp" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textColor="#000" android:textSize="18sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Feature : " android:textColor="#000" android:textSize="18sp" /> <TextView android:id="@+id/tvFeature" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textColor="#000" android:textSize="18sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Country : " android:textColor="#000" android:textSize="18sp" /> <TextView android:id="@+id/tvCountry" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textColor="#000" android:textSize="18sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="State : " android:textColor="#000" android:textSize="18sp" /> <TextView android:id="@+id/tvState" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textColor="#000" android:textSize="18sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="City : " android:textColor="#000" android:textSize="18sp" /> <TextView android:id="@+id/tvCity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textColor="#000" android:textSize="18sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pincode : " android:textColor="#000" android:textSize="18sp" /> <TextView android:id="@+id/tvPincode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textColor="#000" android:textSize="18sp" /> </LinearLayout> </LinearLayout>

Above main XML file includes one Button and several Text views.

When the user will click the button, we will fetch the address from current latitude and longitude.

We will fill the text views with the information like country, city, state, pin code, zip code etc.

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'.

Please 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.

3. Android Get Latitude And Longitude From Address

Android Get Latitude And Longitude From Address is the today’s main topic.

We will fetch the co ordinates in form of latitude and longitude from the address of the location.

There may be some case where user do not know his/her current location in terms of latitude and longitude but he can write his address.

In such case, you need to fetch the co ordinates from the address given by the user.

This tutorial will guide you how to insert this feature in your android application with easy and simple coding lines.

User will enter the address in the edit box. Our code will get the co ordinates (latitude and longitude) from this address using Address, Geocoder and Message class.

Read Fetched Address

Watch the below video to show how this demo tutorial is working.

Step 1. Geo Coding Class

First of all, make a new class named GeocodingLocation.java

Source code for GeocodingLocation.java is as the following

import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.util.List; import java.util.Locale; public class GeocodingLocation { private static final String TAG = "GeocodingLocation"; public static void getAddressFromLocation(final String locationAddress, final Context context, final Handler handler) { Thread thread = new Thread() { @Override public void run() { Geocoder geocoder = new Geocoder(context, Locale.getDefault()); String result = null; try { List addressList = geocoder.getFromLocationName(locationAddress, 1); if (addressList != null && addressList.size() > 0) { Address address = (Address) addressList.get(0); StringBuilder sb = new StringBuilder(); sb.append(address.getLatitude()).append("

"); sb.append(address.getLongitude()).append("

"); result = sb.toString(); } } catch (IOException e) { Log.e(TAG, "Unable to connect to Geocoder", e); } finally { Message message = Message.obtain(); message.setTarget(handler); if (result != null) { message.what = 1; Bundle bundle = new Bundle(); result = "Address: " + locationAddress + "



Latitude and Longitude :

" + result; bundle.putString("address", result); message.setData(bundle); } else { message.what = 1; Bundle bundle = new Bundle(); result = "Address: " + locationAddress + "

Unable to get Latitude and Longitude for this address location."; bundle.putString("address", result); message.setData(bundle); } message.sendToTarget(); } } }; thread.start(); } }

Above class is primarily using three classes : Geocoder, Address and Message.

Compiler will first start one thread.

Inside this thread, it will create the object of the Geocoder class.

Then it will fetch the latitude and longitude using .getFromLocationName() method.

An object of List class will hold the output given by .getFromLocationName() method. Object of Address class will get output from List class object.

After this, an object of StringBuilder class will fetch co ordinates and than a string variable will finally get latitude and longitude from given address.

Step 2. XML file for main activity

When you create a new project in android studio, system creates two files automatically.

One of them is activity_main.xml.

Copy the below code snippet in activity_main.xml.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#860808" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fff" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:text="Enter Address in below box" android:id="@+id/addressTV" android:textSize="19sp"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/etAdd" android:textColor="#fff" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:text="Rajratna complex Tagore road Rajkot Gujarat India 360002 " /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Erase Box" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:id="@+id/btnErase"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get Latitude Longitude" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:id="@+id/btn"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="19sp" android:textColor="#fff" android:text="Lat Long will appear here" android:id="@+id/tv" android:layout_marginTop="20dp" android:layout_marginLeft="20dp"/> </LinearLayout>

There are some UI widgets in the above file.

Two buttons, two text views and one edit text is present.

In the edit text, user can input the address. By default, I have written one address.

Below this edit text, there will be two buttons. One button will erase the text from the edit text when user clicks it.

Other button will fetch the latitude and longitude from the address when it is clicked.

Step 3. Writing Main File

Write down the below source code in MainActivity.java file

import android.os.Handler; import android.os.Message; 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.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Button button, btnErase; private TextView textView; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.tv); btnErase = findViewById(R.id.btnErase); editText = (EditText) findViewById(R.id.etAdd); btnErase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editText.setText(""); } }); button = (Button) findViewById(R.id.btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { String address = editText.getText().toString(); GeocodingLocation locationAddress = new GeocodingLocation(); locationAddress.getAddressFromLocation(address, getApplicationContext(), new GeocoderHandler()); } }); } private class GeocoderHandler extends Handler { @Override public void handleMessage(Message message) { String locationAddress; switch (message.what) { case 1: Bundle bundle = message.getData(); locationAddress = bundle.getString("address"); Log.d("latttt",locationAddress); break; default: locationAddress = null; } textView.setText(locationAddress); } } }

Looking Main Class Deeply

Consider the below code

private Button button, btnErase; private TextView textView; private EditText editText;

Compiler will create the objects of Button, Text view and Edit text etc. classes.

Now look at the below code

btnErase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editText.setText(""); } });

Compiler will execute the above code when the user clicks on the erase button.

It will set the null or empty text on the edit text.

Now read the following code structure

button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { String address = editText.getText().toString(); GeocodingLocation locationAddress = new GeocodingLocation(); locationAddress.getAddressFromLocation(address, getApplicationContext(), new GeocoderHandler()); } });

When the user clicks “GET LATITUDE LONGITUDE” button, compiler will run the above code lines.

It will first get the address in the string format from the edit text.

Then it will create the object of the GeocodingLocation class.

Then compiler will user .getAddressFromLocation() method.

.getAddressFromLocation() method will get the address in string format as the first parameter, application context as a second parameter and object of GeocoderHandler() as the last parameter.

Below is the code writings for GeocoderHandler class.

private class GeocoderHandler extends Handler { @Override public void handleMessage(Message message) { String locationAddress; switch (message.what) { case 1: Bundle bundle = message.getData(); locationAddress = bundle.getString("address"); Log.d("latttt",locationAddress); break; default: locationAddress = null; } textView.setText(locationAddress); } }

Here, handleMessage() method will get the object of the Message class in it’s first parameter.

Then compiler will get the data from this object using Bundle class.

From this bundle, compiler will get the latitude and longitude in the string format using .getString(“address”) class.

Finally, compiler will set this latitude and longitude in the text view.