About Me

My photo
Talk to me... you will know

Tuesday, November 29, 2011

Distance Calculator using google api distance matrix, and json parsing




Was working on google api for my project to calculate the distance between 2 places.. Google maps has that functionality but i needed a sneak peek into the api for that.. I did a little research for the same and found out that they used json objects in Distance Matrix for the same. So i tried to learn json parsing which is very simple by the way. You will need the json jar file to run this and its quite good at calculating distance between any two places on earth...
Try it out.. Its very simple.


the data from the url for 2 places say noida to delhi will be a json object of the format


You just need to know how to parse through and get thae data. :)

//JSON object :

{
   "destination_addresses" : [ "Bokaro, झारखण्ड, India" ],
   "origin_addresses" : [ "Noida, Delhi, India" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,201 km",
                  "value" : 1200769
               },
               "duration" : {
                  "text" : "15 hours 19 mins",
                  "value" : 55119
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}


//JSONInterface.java

package com.distanceMatrix;


import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.*;


public class JSONInterface 
{
Integer tem;
Float dist;


private static String readAll(Reader rd) throws IOException 
{
   StringBuilder sb = new StringBuilder();
   int cp;
   while ((cp = rd.read()) != -1) 
   {
     sb.append((char) cp);
   }
   return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException 
{
   InputStream is = new URL(url).openStream();
   try 
   {
     BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
     String jsonText = readAll(rd);
     JSONObject json = new JSONObject(jsonText);
     return json;
   }
   finally 
   {
     is.close();
   }
}


public float calcDistance(StringBuffer beg, StringBuffer end) 
{
JSONObject json=null;
try 
{

json = readJsonFromUrl("https://maps.googleapis.com/maps/api/distancematrix/json?origins="+beg+"&destinations="+end+"&mode=driving&sensor=false");
json.get("rows");
JSONArray arr=null;
arr = json.getJSONArray("rows");
tem=(Integer)arr.getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").getInt("value");
dist=(float)tem/1000;
}
catch (JSONException e) 
{
e.printStackTrace();

catch (IOException e)
{
    e.printStackTrace();
}
return dist;
}
}




//JSONDiatanceCalculator.java


package com.distanceMatrix;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class JSONDiatanceCalculator 
{
static String beg,end;
static StringBuffer start=new StringBuffer(), stop=new StringBuffer();
static float totDistance;
public static void main(String args[])
{
JSONInterface ji=new JSONInterface();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter the source place : ");
beg=br.readLine();
System.out.println("Enter the distance place : ");
end=br.readLine();
start.append(beg);
stop.append(end);
for(int i=0; i<start.length(); i++)
{
if(start.charAt(i)==' ')
{
start.deleteCharAt(i);
start.insert(i, "%20");
}
}
for(int i=0;i<stop.length();i++)
{
if(stop.charAt(i)==' ')
{
stop.deleteCharAt(i);
stop.insert(i, "%20");
}
}
totDistance=ji.calcDistance(start,stop);
System.out.println("The distance between "+beg+" and "+end+" is = "+totDistance);
}
catch(IOException e)
{
System.out.println("Improper place value set..");
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("Json type exception");
e.printStackTrace();
}
}
}

There was an error in this gadget