RSS

Android: How to get Address from geolocation using Geocoder

12 Mar

Class: HttpRetriever

public class HttpRetriever {
	private DefaultHttpClient client = new DefaultHttpClient();

	public String retrieve(String url) {
		HttpGet getRequest = new HttpGet(url);
		try {
			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w(getClass().getSimpleName(), "Error " + statusCode
						+ " for URL " + url);
				return null;
			}
			HttpEntity getResponseEntity = getResponse.getEntity();

			if (getResponseEntity != null) {
				return EntityUtils.toString(getResponseEntity);
			}
		} catch (IOException e) {
			getRequest.abort();
			Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
		}
		return null;

	}
}

Method: getAddressFromGPSData

public static final String GOOGLE_GEOCODER = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";

public static String getAddressFromGPSData(double lat, double longi) {
		HttpRetriever agent = new HttpRetriever();
		String request = GOOGLE_GEOCODER + lat + ","
				+ longi + "&sensor=true";
		// Log.d("GeoCoder", request);
		String response = agent.retrieve(request);
		String formattedAddress = "";
		if (response != null) {
			Log.d("GeoCoder", response);
			try {
				JSONObject parentObject = new JSONObject(response);
				JSONArray arrayOfAddressResults = parentObject
						.getJSONArray("results");
				JSONObject addressItem = arrayOfAddressResults.getJSONObject(0);
				formattedAddress = addressItem.getString("formatted_address");
			} catch (JSONException e) {

				e.printStackTrace();
			}

		}

		// Log.d("GeoCoder", response);
		return formattedAddress;
	}
 
5 Comments

Posted by on March 12, 2012 in Uncategorized

 

5 responses to “Android: How to get Address from geolocation using Geocoder

  1. elad

    March 4, 2013 at 1:35 pm

    wow awsome!!!! just what i need…. 😉 is it optional to do the oposit??? get geo location from an adress??????

     
    • androidstream

      March 4, 2013 at 2:37 pm

      Yes.. that is feasible by geocoding.

       
  2. zhouzhou

    March 19, 2013 at 6:22 pm

    does this need a google api key to run? thx!

     
    • androidstream

      March 19, 2013 at 7:09 pm

      No

       
      • zhouzhou

        March 19, 2013 at 8:43 pm

        androidstream,Thanks!

         

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: