Thursday, October 20, 2011

Simple Reverse Geo-coding in Java using Google Map

The Java Class

package geo;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class MyGeo {
public static void main(String ar[]) throws Exception {
System.out.println(new MyGeo().getAddress("13.031067,80.239656"));
}
public String getAddress(String latlong){
String address = null;
String gURL = "http://maps.google.com/maps/api/geocode/xml?latlng=" + latlong + "&sensor=true";
try {
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
DocumentBuilder db = df.newDocumentBuilder();
Document dom = db.parse(gURL);
Element docEl = dom.getDocumentElement();
NodeList nl = docEl.getElementsByTagName("result");
if (nl != null && nl.getLength() > 0){
address=((Element)nl.item(0)).getElementsByTagName("formatted_address").item(0).getTextContent();
for(int i=0;i<nl.getLength();i++){
String temp=((Element)nl.item(i)).getElementsByTagName("formatted_address").item(0).getTextContent();
}
}
} catch (Exception ex) {
address = "Err";
}
return address;
}
public String getAddress(String lat, String lon) {
return getAddress(lat+ "," + lon);
}
public String getAddress(double lat, double lon) {
return getAddress("" + lat, "" + lon);
}
}

Run
>java geo.MyGeo
Venkatanarayana Rd, CIT Nagar, Chennai, Tamil Nadu, India


Note: Google has some restriction in this web-service call like number of requests per day from one IP.
Ref: http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding

5 comments:

  1. What are jar file need to add to run the above program

    ReplyDelete
  2. It's working thank you dude. Very nice blog

    ReplyDelete
  3. Working! However i need to get address for all the Latitude and Longitude, If not available then i want the nearby address, is it possible for me?

    ReplyDelete
  4. It's working thank you dude. Very nice blog

    ReplyDelete
  5. Sir, your tutorial is very well. I implemented Simple Geo-coding in Java using Google Map. But didn't get output. Please give any suggestion....

    ReplyDelete