Friday 24 May 2013

Android - Google Maps API V2 (Part -3) : Geocoding and Reverse Geocoding


In previous article, we plotted hard coded latitude-longitude coordinates on map.

Here we will delve into
1. Geocoding : Retrieving Lat-Lng from a known address
2. Reverse Geocoding : Retrieve Address from known Lat-Lng coordinates

Well, there are two approaches to achieve the same :
1. Using Geocoder Class
2. Using Google Maps APIs

Lets look at both of them and the scenario where each can be used.

Approach 1 : Using Geocoder Class


Geocoding : Is generally required while accepting address from user.

public void geocodeAddress(String addressInput) {
        Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
 List
addresses = null; try { addresses = geocoder.getFromLocationName(addressInput,1); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); double lat = address.getLatitude(); double lng = address.getLongitude(); } }

getFromLocationName() is our saviour here :D It just accepts address and returns a list of Addresses that describe the location. You can also specify the number of results you want too have, which is 1 in above case!
Phew! And you are done. Using methods of Address class, we can retrieve lat-lng. Complete address can also be retrieved using 
String title = address.getAddressLine(0)+address.getAdminArea()+address.getCountryName();

Reverse Geocoding :Is required when user taps on map and you need to show the location that he tapped.

Once user taps, we have lat/lng available. To retrieve address :
public String reverseGeocode(double latitude, double longitude) {
 Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
 List
addresses = null; String result = null; try { // Call the synchronous getFromLocation() method by passing in the lat/long values. addresses = geocoder.getFromLocation(latitude, longitude, 1); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); // Format the first line of address (if available), city, and country name. result = String.format("%s, %s, %s", address .getMaxAddressLineIndex () > 0 ? address.getAddressLine(0) : "", address.getAdminArea(), address.getCountryName()); } return result; }
Approach 2 : Using Google Maps APIs

Performing same tasks using Google Maps APIs require making Post request to google servers, which return JSON response. Just Parse it to get details.


More Details on this can be found here.
Geocoding Strategies explains when to use which approach.


Problem that generally occurs while using Geocoder class!


Happy Coding!
~Divya

No comments:

Post a Comment

Would love to hear from you. Leave a comment :)