Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Using Geocoding and Reverse GeocodingBack to Android Cookbook Home | Up to Chapter: Location and Map Applications

Author: Nidhin Jose Davis ('josnidhin')
In Published Edition? Yes
FormatLanguage: WikiFormat

Using Geocoding and Reverse Geocoding

Problem

How to Geocode and Reverse Geocode on Android

Solution

The solution is to use Geocoder class.

Discussion

Geocoding is the process of finding the geographical coordinates (latitude and longitude) of given address or location.

Reverse Geocoding as you might have guessed is the opposite if Geocoding. In this case a pair of latitude and longitude is converted into an address or location.

In order to Geocode or Reverse Geocode the first thing to do is to import the proper package.

import android.location.Geocoder;

The Geocoding or Reverse Geocoding should not be done on the UI thread as it might cause the system to display an Application Not Responding (ANR) dialog to the user. So it has to done in separate thread.

To Geocode

Geocoder gc = new Geocoder(context);

if(gc.isPresent()){
  List<Address> list = gc.getFromLocationName("1600 Amphitheatre Parkway, Mountain View, CA", 1);

  Address address = list.get(0);

  double lat = address.getLatitude();
  double lng = address.getLongitude();
}

To Reverse Geocode

Geocoder gc = new Geocoder(context);

if(gc.isPresent()){
  List<Address> list = gc.getFromLocation(37.42279, -122.08506,1);

  Address address = list.get(0);

  StringBuffer str = new StringBuffer();
  str.append("Name: " + address.getLocality() + "\n");
  str.append("Sub-Admin Ares: " + address.getSubAdminArea() + "\n");
  str.append("Admin Area: " + address.getAdminArea() + "\n");
  str.append("Country: " + address.getCountryName() + "\n");
  str.append("Country Code: " + address.getCountryCode() + "\n");

  String strAddress = str.toString();
}

See Also