Android Get Address with Street Name, City for Location with Geocoding

Last modified on October 16th, 2014 by Joe.

In this Android tutorial, I will walk you through how to find the address based on the mobile location. We have got GPS or network provider in the Android device and we can use that to get the current location in terms of latitude and longitude. Using the latitude and longitude we can get the address by Google Geocoding API.

Android-Geocode-Location-Address

Download the Example Android Application

Android Reverse Geocode Location Project

Geocoding

Geocoding is the process of converting the addresses (postal address) into geo coordinates as latitude and longitude. Reverse geocoding is converting a geo coordinate latitude and longitude to an address. In this tutorial we will be doing reverse geo coding and get the addresses of the passed coordinates.

Android Reverse Geocoding Example to find Address

Step1: Define Permissions

We need location access permission to find the latitude and longitude of the Android device. Following two lines are the key to give permission to access the location.

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

So the complete manifest file will be as below:

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Step 2: Accessing the Geo Location for Lat and Long

Following class is the key element in accessing the latitude and longitude of the Android device. It implements the LocationListener and gets the location coordinate updates. We have designed our requirement not to be a continous update for location. On demand we will get the location coordinates.

AppLocationService.java

package android.javapapers.com.androidgeocodelocation;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class AppLocationService extends Service implements LocationListener {

    protected LocationManager locationManager;
    Location location;

    private static final long MIN_DISTANCE_FOR_UPDATE = 10;
    private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

    public AppLocationService(Context context) {
        locationManager = (LocationManager) context
                .getSystemService(LOCATION_SERVICE);
    }

    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,
                    MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(provider);
                return location;
            }
        }
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

Step 3: Reverse Geocoding to get Location Address

Following class is the key element for reverse geocoding to get the address for the passed latitude and longitude coordinates. We access the Geocoder Google API for reverse geocoding and get every line of address like street, city, pin / zip code and etc.

LocationAddress.java

package android.javapapers.com.androidgeocodelocation;

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 LocationAddress {
    private static final String TAG = "LocationAddress";

    public static void getAddressFromLocation(final double latitude, final double longitude,
                                              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<Address> addressList = geocoder.getFromLocation(
                            latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }
                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());
                        result = sb.toString();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable connect to Geocoder", e);
                } finally {
                    Message message = Message.obtain();
                    message.setTarget(handler);
                    if (result != null) {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n\nAddress:\n" + result;
                        bundle.putString("address", result);
                        message.setData(bundle);
                    } else {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n Unable to get address for this lat-long.";
                        bundle.putString("address", result);
                        message.setData(bundle);
                    }
                    message.sendToTarget();
                }
            }
        };
        thread.start();
    }
}

Step 4: Android UI

How these pieces fit together is with the following Android activity.

MyActivity.java

package android.javapapers.com.androidgeocodelocation;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MyActivity extends Activity {

    Button btnGPSShowLocation;
    Button btnShowAddress;
    TextView tvAddress;

    AppLocationService appLocationService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        tvAddress = (TextView) findViewById(R.id.tvAddress);
        appLocationService = new AppLocationService(
                MyActivity.this);

        btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
        btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Location gpsLocation = appLocationService
                        .getLocation(LocationManager.GPS_PROVIDER);
                if (gpsLocation != null) {
                    double latitude = gpsLocation.getLatitude();
                    double longitude = gpsLocation.getLongitude();
                    String result = "Latitude: " + gpsLocation.getLatitude() +
                            " Longitude: " + gpsLocation.getLongitude();
                    tvAddress.setText(result);
                } else {
                    showSettingsAlert();
                }
            }
        });

        btnShowAddress = (Button) findViewById(R.id.btnShowAddress);
        btnShowAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                Location location = appLocationService
                        .getLocation(LocationManager.GPS_PROVIDER);

                //you can hard-code the lat & long if you have issues with getting it
                //remove the below if-condition and use the following couple of lines
                //double latitude = 37.422005;
                //double longitude = -122.084095

                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    LocationAddress locationAddress = new LocationAddress();
                    locationAddress.getAddressFromLocation(latitude, longitude,
                            getApplicationContext(), new GeocoderHandler());
                } else {
                    showSettingsAlert();
                }

            }
        });

    }

    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                MyActivity.this);
        alertDialog.setTitle("SETTINGS");
        alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        MyActivity.this.startActivity(intent);
                    }
                });
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        alertDialog.show();
    }

    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");
                    break;
                default:
                    locationAddress = null;
            }
            tvAddress.setText(locationAddress);
        }
    }
}

Android UI layout file to show the address and location

<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=".MyActivity">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:id="@+id/btnGPSShowLocation"
        android:layout_toEndOf="@+id/textView"
        android:layout_marginTop="53dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Address"
        android:id="@+id/btnShowAddress"
        android:layout_toEndOf="@+id/tvAddress"
        android:layout_below="@+id/btnGPSShowLocation"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvAddress"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="134dp"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

Key Points to Note for Geocoding

Example Geo coordinates Latitude and Longitude with respective location address:

Latitude, Longitude: 38.898748, -77.037684
Location Address:
1600 Pennsylvania Ave NW 
Washington DC 20502

Latitude, Longitude: 34.101509, -118.32691
Location Address:
Hollywood Blvd & Vine St 
Los Angeles CA 90028

Download the Example Android Application

Android Reverse Geocode Location Project

Comments on "Android Get Address with Street Name, City for Location with Geocoding"

  1. Jitendra Singh says:

    Awesome demo Sir Ji…

  2. Firoz Shaikh says:

    Sir, My one Suggestion,
    if you don’t mind,
    try using findViewById(R.id.btnGPSShowLocation).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
    //if you want to manage only onClick no other use in java file
    }
    }
    OR
    in layout xml, put OnClick property in atlest one post. so that people can get another way also if they might like.

  3. omkar says:

    Nice demo!

  4. […] how to find latitude/longitude for a give address location. In a previous tutorial we learnt about reverse geocoding to find address for a latitude/longitude. This tutorial is a reverse of […]

  5. sunil says:

    the code have fatal exception

  6. hasan says:

    The app is continously asking me to enable location provider, but i have enabled my gps and wifi, and i am trying it on a real device

  7. sana says:

    i have the same problem as hasan has the app when tried on real device says enable location provider inspite of gps n wifi being enabled.. can u please solve our query …

    thankyou

  8. dharmesh says:

    Thenkyu sir,i use this tutorial

  9. Ali says:

    it does not show city name why?

  10. Aniket says:

    Thank you very much sir….. Simple n Effective.. Gr8 Work

  11. rakesh says:

    Settings.ACTION_LOCATION_SOURCE_SETTINGS
    i got error ;
    what i will do

  12. Vikram Singh says:

    hello sir
    i am getting settings Dialogs while my Location Provided is already Enabled.

  13. Ramu says:

    Hello Sir,

    I am also getting same issue as it is opening settings and even enabled the GPS i am not getting the location.
    Can anyone help to solve this issue.

  14. Ivan says:

    Hello Sir,

    My friend’s device can get the address, but mine can’t. Is it the API level of the device problem? Cause my friend’s device API level is 19, but mine is API 18. Can someone help me?

  15. balaji.r.s says:

    sir,
    i am too getting the same problem what they mentioned above as open setting even it is ON.

  16. Gab says:

    I am getting the same issue as the dialogue box keep prompting although I have already switched on the GPS and Wi-fi on my mobile. Any ideas?

  17. Meenu says:

    For those, who are not getting lattitude, longitude values and address too, try using NETWORK_PROVIDER instead of GPS_PROVIDER in your codings. Comment the else part in codings that call the settings. Turn Wi-Fi on in your mobile and try, it will work. I did so and it worked. Thank you!

    Thank you so much for this tutorial.

  18. Arun Kumar says:

    Hello Sir,

    Why u are extending service? You did not start service at all in above program.

  19. Swarn Singh says:

    Use this for perfect work…
    and same for address button click

    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
    Location gpsLocation = appLocationService
    .getLocation(LocationManager.GPS_PROVIDER);

    Location networkLocation = appLocationService
    .getLocation(LocationManager.NETWORK_PROVIDER);
    if (gpsLocation != null) {
    double latitude = gpsLocation.getLatitude();
    double longitude = gpsLocation.getLongitude();
    String result = “Latitude: ” + gpsLocation.getLatitude()
    + ” Longitude: ” + gpsLocation.getLongitude();
    tvAddress.setText(result);
    } else if (networkLocation != null) {
    double latitude = networkLocation.getLatitude();
    double longitude = networkLocation.getLongitude();
    String result = “Latitude: ”
    + networkLocation.getLatitude() + ” Longitude: ”
    + networkLocation.getLongitude();
    tvAddress.setText(result);
    } else {
    showSettingsAlert();
    }
    }
    });

  20. Milan says:

    this solution solve all the errror

    gps = new GPSTracker(MainActivity.this);
    if(gps.canGetLocation()){

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

    String result = “Latitude: ” + latitude +
    ” Longitude: ” + longitude;
    tvAddress.setText(result);

    Use this Class insted of AppLocationService.java this class

    public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    boolean isGPSEnabled = false;

    boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    protected LocationManager locationManager;

    public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
    }

    public Location getLocation() {
    try {
    locationManager = (LocationManager) mContext
    .getSystemService(LOCATION_SERVICE);

    isGPSEnabled = locationManager
    .isProviderEnabled(LocationManager.GPS_PROVIDER);

    isNetworkEnabled = locationManager
    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isGPSEnabled && !isNetworkEnabled) {
    } else {
    this.canGetLocation = true;
    if (isNetworkEnabled) {
    locationManager.requestLocationUpdates(
    LocationManager.NETWORK_PROVIDER,
    MIN_TIME_BW_UPDATES,
    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    Log.d(“Network”, “Network”);
    if (locationManager != null) {
    location = locationManager
    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location != null) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    }
    }
    }
    if (isGPSEnabled) {
    if (location == null) {
    locationManager.requestLocationUpdates(
    LocationManager.GPS_PROVIDER,
    MIN_TIME_BW_UPDATES,
    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    Log.d(“GPS Enabled”, “GPS Enabled”);
    if (locationManager != null) {
    location = locationManager
    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    }
    }
    }
    }
    }

    } catch (Exception e) {
    e.printStackTrace();
    }

    return location;
    }

    public void stopUsingGPS(){
    if(locationManager != null){
    locationManager.removeUpdates(GPSTracker.this);
    }
    }
    public double getLatitude(){
    if(location != null){
    latitude = location.getLatitude();
    }

    return latitude;
    }

    public double getLongitude(){
    if(location != null){
    longitude = location.getLongitude();
    }

    return longitude;
    }

    public boolean canGetLocation() {
    return this.canGetLocation;
    }

    public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle(“GPS is settings”);

    // Setting Dialog Message
    alertDialog.setMessage(“GPS is not enabled. Do you want to go to settings menu?”);

    // On pressing Settings button
    alertDialog.setPositiveButton(“Settings”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog,int which) {
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    mContext.startActivity(intent);
    }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    dialog.cancel();
    }
    });

    // Showing Alert Message
    alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
    return null;
    }

    }

  21. Nishu says:

    WTF it only keep asking to enable location provider and never show location..

  22. vikas rai says:

    It doesn’t work. it asks me to enable location provider.please fix it.

  23. krishna priya kota says:

    In addition to changing your settings in emulator, go to DDMS and set latitude and longitude in emulator control and click on send. This code works then.

  24. Mukesh says:

    How we get it?

  25. Saiteja says:

    Hi,
    It worked like a miracle. I just followed your steps.
    But It is taking little bit of time (2sec, In my case) to get address. Is it the normal latency or it its happening in my case? Please provide if there is any faster way / new alternative.

    Thank you

  26. Janitra says:

    Hi,
    for all whose getting a Setting Dialog when using this code, why don’t you try using LocationManager.Network_Provider?

    in this code, the MainActivity is using GPS_Provider.
    because GPS is often taking a long time to get our location
    I can sit here in my office and waiting all day for gps to get my location, and still nothing
    try to change it to Network_Provider and it’ll work

  27. Usha says:

    Thank You so much :) It helped me lot :) :)

  28. Subhash says:

    Hi,
    can we find the longitude and latitude of a current location with no internet connectivity.??
    if yes,can you provide me the code.

    thanks in advance

Comments are closed for "Android Get Address with Street Name, City for Location with Geocoding".