Java program to get Latitude and Longitude

Thursday, September 20, 2012

As you know, lot of things got easier with the invention of Google Maps i.e.; we can locate a particular house/shop/company etc. I'm not sure whether you're aware hot it works? It all works based on the latitude and longitude points/values. Latitude represents the north-south point on the earth and Longitude represents the east-west point on the earth.

There are several APIs to get the latitude and longitude values programatically. But I've developed a small standalone application which gets the latitude and longitude values from Google maps.

It's very simple, all I'm doing is - polling the Google maps URL with the post code/search key and reading the response received, if it's successful.

import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.Document;

/**
 * This class will get the lat long values.
 * @author SANTHOSH REDDY MANDADI
 * @version 1.0
 * @since 20-Sep-2012
 */
public class LatLng
{
  public static void main(String[] args) throws Exception
  {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Please enter a location:");
    String postcode=reader.readLine();
 String latLongs[] = getLatLongPositions(postcode);
    System.out.println("Latitude: "+latLongs[0]+" and Longitude: "+latLongs[1]);
  }
  
  public static String[] getLatLongPositions(String address) throws Exception
  {
    int responseCode = 0;
    String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=true";
    URL url = new URL(api);
    HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
    httpConnection.connect();
    responseCode = httpConnection.getResponseCode();
    if(responseCode == 200)
    {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
      Document document = builder.parse(httpConnection.getInputStream());
      XPathFactory xPathfactory = XPathFactory.newInstance();
      XPath xpath = xPathfactory.newXPath();
      XPathExpression expr = xpath.compile("/GeocodeResponse/status");
      String status = (String)expr.evaluate(document, XPathConstants.STRING);
      if(status.equals("OK"))
      {
         expr = xpath.compile("//geometry/location/lat");
         String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
         expr = xpath.compile("//geometry/location/lng");
         String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
         return new String[] {latitude, longitude};
      }
      else
      {
         throw new Exception("Error from the API - response status: "+status);
      }
    }
    return null;
  }
}
Output
>java LatLng
Please enter a location:
600017, Chennai
Latitude: 13.0412658 and Longitude: 80.2338514

Please put your comments and questions below.

If you've sometime, why don't you checkout my other Java programs

31 comments:

  1. Replies
    1. Hi - please input the postcode for which you need to extract the lat long values. As you can see in the output above, W3 5DE is a UK post code.

      Delete
  2. How about Indian post code it will work?

    ReplyDelete
    Replies
    1. Yes, it works in deed. Since, our (Indian) postcodes are numbers, better to force "India" at the end i.e.; 508234, India.

      Just to be clear, the above program works even with just a city, place etc... if you look at the URL, we're just passing a parameter called "q" to Google.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Thank now i did.........
      only replace String link by - String link="https://www.google.com/maps/place?q="+URLEncoder.encode(postcode, "UTF-8");

      Delete
  3. hi i need to get latitude and longitude for my current location with out any input...can u please suggest me.....

    ReplyDelete
    Replies
    1. you can use google latitude ,login with your email id set google badge for your account use that user id on your application

      Delete
    2. hi Rajkumar,
      I have seen your Question and Answer. Have you successfly get the location of phone.
      reply me at dear.oracledba@gmail.com

      Delete
    3. Hi guys - I've updated the program today... You can get the lat longs for any location now, Thanks

      Delete
  4. hi i m getting
    Please enter a postcode:
    202002,india
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
    ex out of range: -1
    at java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:
    873)
    at java.lang.StringBuffer.substring(StringBuffer.java:433)
    at latitude.main(latitude.java:35)
    Press any key to continue . . .

    how to resolve this error

    ReplyDelete
  5. i find the simple way to get this result on u r post..

    ReplyDelete
  6. Hi,

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:868)
    at java.lang.StringBuffer.substring(StringBuffer.java:412)
    at parse.par.main(par.java:35)


    I am getting this error can anyone help me out pls

    ReplyDelete
    Replies
    1. hey same exception i got ..
      could u able to solve?

      Delete
    2. Hi guys - I've updated the program today... You can get the lat longs for any location now, Thanks

      Delete
  7. Since the link "http://maps.google.com/maps" is used , can we still use this code without google maps

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Sir , I run this code and enter value 411011 Pune but error will display as given bellow Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:868)
    at java.lang.StringBuffer.substring(StringBuffer.java:412)
    at LatLong.main(LatLong.java:35)

    ReplyDelete
    Replies
    1. how to resolve this error

      Delete
    2. Hi guys - I've updated the program today... You can get the lat longs for any location now, Thanks

      Delete
  10. This comment has been removed by the author.

    ReplyDelete
  11. I want code for I give latitude and longitude manually then return place exact location. Please sir my emai id is pravinfatak123@gmail.com

    ReplyDelete
  12. Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.AbstractStringBuilder.substring(Unknown Source)
    at java.lang.StringBuffer.substring(Unknown Source)
    at LongLatService.main(LongLatService.java:38)

    how do i resolve this error???

    ReplyDelete
    Replies
    1. Hi guys - I've updated the program today... You can get the lat longs for any location now, Thanks

      Delete
  13. Please enter a postcode:
    600106,India
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:868)
    at java.lang.StringBuffer.substring(StringBuffer.java:412)
    at LatLong.main(LatLong.java:39)
    Java Result: 1


    This is my output can anybody solve this problem....

    ReplyDelete
    Replies
    1. Hi guys - I've updated the program today... You can get the lat longs for any location now, Thanks

      Delete
  14. guys i also got this same Exception , anybody get the solution for this ?

    ReplyDelete
    Replies
    1. Hi guys - I've updated the program today... You can get the lat longs for any location now, Thanks

      Delete
  15. Hi guys - I've updated the program today... You can get the lat longs for any location now, Thanks

    ReplyDelete
  16. Hi
    I need to construct address form given lat long
    plz help me out...
    Thanx..

    ReplyDelete