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

30 comments:

Bob Mueser said...

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.

Android Er said...

hello Bob Mueser,

I have no idea about WOEID right now! Sorry.

Ivan Tasev said...

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

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

Pavie Negi said...

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

Android Er said...

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.

Serhat said...

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

Android Er said...

hello Serhat,

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

VanTrung said...

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

Android Er said...

hello VanTrung,

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

jonh said...

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?

Android Er said...

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.

Cyclopes said...

check out this link will sure helps

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

paresh patel said...

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

Unknown said...

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

aNaNd said...

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

Anonymous said...

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

kiran kirve said...

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

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

Anonymous said...

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

BINAL MODI said...

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.

Andr.oid Eric said...

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.

Shyam Sasikumar said...

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

Andr.oid Eric said...

hello Shyam Sasikumar,

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

Prabhjit Oberoi said...

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

Vikash said...

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

Usman Shahid said...

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

Anonymous said...

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

jeremiah escamillan said...

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"

Andr.oid Eric said...

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.

Rakesh said...

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

Anonymous said...

This code does not work