Wednesday, February 9, 2011

Get address from location using Geocoder

Geocoder is a class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.

The getFromLocation(double latitude, double longitude, int maxResults) method returns an array of Addresses that are known to describe the area immediately surrounding the given latitude and longitude. The returned addresses will be localized for the locale provided to this class's constructor.

The returned values may be obtained by means of a network lookup. The results are a best guess and are not guaranteed to be meaningful or correct. It may be useful to call this method from a thread separate from your primary UI thread.

It's a exercise getting reversed address from a given location (LATITUDE and LONGITUDE), maxResults is set to one.

Get address from location using Geocoder

package com.exercise.AndroidFromLocation;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidFromLocation extends Activity {

double LATITUDE = 37.42233;
double LONGITUDE = -122.083;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
       TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
       TextView myAddress = (TextView)findViewById(R.id.myaddress);
      
       myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
       myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
      
       Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);

       try {
  List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
 
  if(addresses != null) {
   Address returnedAddress = addresses.get(0);
   StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
   for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
   }
   myAddress.setText(strReturnedAddress.toString());
  }
  else{
   myAddress.setText("No Address returned!");
  }
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  myAddress.setText("Canont get Address!");
 }

   }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Location"
   android:background="#505050"
   />
<TextView
   android:id="@+id/mylatitude"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView
   android:id="@+id/mylongitude"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Address"
   android:background="#505050"
   />
<TextView
   android:id="@+id/myaddress"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
</LinearLayout>


Download the files.

Related Article:
- Get list of address from location using Geocoder

Updated@20150916:
Find addresses of given latitude and longitude using android.location.Geocoder
Example allow users to enter latitude and longitude, then find the addresses that are known to describe the area immediately surrounding the given latitude and longitude,

36 comments:

  1. This is pretty cool, however, I have a question. Can this (or something similar) be used to translate the Lat & long into a WOEID? I need to pass that to Yahoo to get weather conditions. Currently, I'm using another Yahoo api for that, but if I can use something native to the Android OS, it would probably be faster.

    ReplyDelete
  2. hello Bob Mueser,

    I have no idea about WOEID right now! Sorry.

    ReplyDelete
  3. I would like to share with you this simple google geocoding and reverse geocoding tool:

    http://mapsys.info/geocoding-tool/

    ReplyDelete
  4. i tried this code but it shows Exception "Can not get Address".
    Please Help...

    ReplyDelete
  5. hello Pavie Negi,

    "Can not get Address" means Google have no record of the address.
    - double check your input data; is it correct and in correct format?
    - Clarify in web version, http://maps.google.com/. Suppose both have the same return.

    ReplyDelete
  6. i got same error . i cant get address.i am using android 2.2 emulator.Can you help me about this situation?

    ReplyDelete
  7. hello Serhat,

    Can I know the address (LATITUDE and LONGITUDE) of your input?

    ReplyDelete
  8. Hi,
    i got same error . i cant get address.i am using android 2.2 (Google APIS 2.2) emulator.Can you help me about this situation?
    I use Lat: 37.42233 And Lng: -122.083

    ReplyDelete
  9. hello VanTrung,

    Can you help test on true device? In my tests (test, and test again), it doesn't always work on emulator!

    ReplyDelete
  10. Hi,
    I only test on emulator. I haven't a true divice. But, i think program can run on true device then it can also run on Emulator. Demo of you are test on Emulator >>> success?

    ReplyDelete
  11. hello jonh,

    I tested this again recently (many ppl complain it cannot get service on emulator), found it not always work on emulator - sometimes ok, sometimes not ok.

    But work on Nexus One.

    ReplyDelete
  12. check out this link will sure helps

    http://stackoverflow.com/a/9173488/1151312

    ReplyDelete
  13. i tried this code
    but this will throws IOException
    Pleaze anyone can help me

    ReplyDelete
  14. This application crashes when i open it in the application...it works fine if I only display the co - ordinates but when I uncomment the lines after Geocoder it crashe sin the phone....

    ReplyDelete
  15. I had get some code from this and It's working for me...thanks

    ReplyDelete
  16. The code gives exception i.e cannot get Address,please help me....

    ReplyDelete
  17. addresses = geocoder1.getFromLocation(latitude,
    longitde, 1);

    this function is not returning proper address wht to do for it

    ReplyDelete
  18. this code works fine on emulator
    but gives stops on phone saying that "unfortuanetly application closed"

    ReplyDelete
  19. I have tried on my android mobile and also on emulator. but
    Can not get Address!
    It shows Service not available message. And exception From java.io.IOException class.

    ReplyDelete
  20. hello BINAL MODI,

    it throw IOException if the network is unavailable or any other I/O problem occurs. It need internet connection to use Geocoder.

    And also, sometimes it cannot get address, may be the service not available at that moment.

    ReplyDelete
  21. I have tried this code but always emulator is showing the error "The application stopped unexpectedly please try again"...is there is any permission problem
    what is the user-permissions for this...?

    Please help..

    ReplyDelete
  22. hello Shyam Sasikumar,

    no permission need. Do you know any error return in LogCat?

    ReplyDelete
  23. this reverse geocoding worked in my case!!..thank u soo much

    ReplyDelete
  24. I am not able to get address of srinagar using latitude and longitude
    34.0836581,74.79736809999997 (it is the city centre of srinagar)

    ReplyDelete
  25. On my device, once it worked but then it had started to throw error, service not available.
    In your code, getting the catch error

    ReplyDelete
  26. Its working absolutely fine on my emulator n showing correct address bt its not working on my mobile...there it shows "cannot get address"...wht should i do...plzz help...!!!!!

    ReplyDelete
  27. haloo . i try your code i have error at this line = Address returnedAddress = addresses.get(0); pls help me :)
    it says in LOGCAT "IndexOutofBoundsExeption: Invalid index 0, size 0"

    ReplyDelete
  28. hello jeremiah escamillan,

    getFromLocation (double latitude, double longitude, int maxResults) return null or empty list if no matches were found or there is no backend service available. So you have to check null and empty also.

    ReplyDelete
  29. addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);

    By this above code it get addresses as square bracket[] only. that's by next bounded exception generated.

    provide a solution

    ReplyDelete
  30. This code does not work

    ReplyDelete
  31. hi all m getting timed out exceptin while convert lat and longitude to address :( :( can anyone help me on this

    ReplyDelete
  32. Hi, Could you please help me with this similar issue?
    I want to write a program where the user can input the latitude and longitude data and get the location in a text view on a button click.

    ReplyDelete
  33. Hello, Could you please help ?

    I am getting postal code as null while passing lat long value.

    ReplyDelete
  34. THANK YOU SO MUCH. After two days of searching and coding I got my location finder finally working because your code sir. :)

    ReplyDelete
  35. for io exception be it may be possible that internet connection is not well.for my app it was the cause for io exception

    ReplyDelete