Google is providing Distance Matrix Web Service for finding distances between places. You can find the documentation of that REST service here. In this tutorial I am going to explain how to use that service using java.

Program Flow

  1. Form Get request to Google server
  2. Get Response 
  3. Convert Response to Java Pojo Classes
  4. Use those Pojo classes for your own logic
Find the project at below link and execute GmapDistance.java file.

Get Url

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling

Parameters

  1. origins — One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, from which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. If you pass coordinates, ensure that no space exists between the latitude and longitude values
  2. destinations — One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, to which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. If you pass coordinates, ensure that no space exists between the latitude and longitude values
  3. key — Your application's API key. This key identifies your application for purposes of quota management
  4. mode — specifies the mode of transport to use when calculating directions (driving (default), walking, bicycling)

Java Code

URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
     outputString += line;
}
System.out.println(outputString);

27 comments:

  1. Wrong Code Dude

    ReplyDelete
    Replies
    1. I have uploaded the working code....Just download the code and run it....If you got any errors then let me know....................be specific about your comments

      Delete
  2. I am not able to download sample project when i click on that link it is redirect me to CurrencyConverter.rar
    https://docs.google.com/file/d/0BwtrZOPVXZZ_QXJHS1ItUjdJTXM/edit

    ReplyDelete
  3. Hi Dasari, can you plz check the link? As i guess its not working.

    ReplyDelete
  4. Hi Dasari, it worked for me, I added some ";" and some println's:

    {; "destination_addresses" : [ "San Francisco, CA, USA", "Victoria, BC, Canada" ],;
    "origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, WA, USA" ],;
    "rows" : [;
    {;
    "elements" : [;
    {;
    "distance" : {;
    "text" : "1,529 km",;
    "value" : 1528699;
    },;
    "duration" : {;
    "text" : "14 hours 57 mins",;
    "value" : 53847;
    },;
    "status" : "OK";
    },;

    {;
    "distance" : {;
    "text" : "115 km",;
    "value" : 114512;
    },;
    "duration" : {;
    "text" : "3 hours 12 mins",;
    "value" : 11506;
    },;
    "status" : "OK";
    };
    ];
    },;
    {;
    "elements" : [;
    {;
    "distance" : {;
    "text" : "1,300 km",;
    "value" : 1299987;
    },;
    "duration" : {;
    "text" : "12 hours 27 mins",;
    "value" : 44807;
    },;
    "status" : "OK";
    },;
    {;
    "distance" : {;
    "text" : "297 km",;
    "value" : 296838;
    },;
    "duration" : {;
    "text" : "4 hours 46 mins",;
    "value" : 17162;
    },;
    "status" : "OK";
    };
    ];
    };
    ],;
    "status" : "OK";
    };

    ReplyDelete
  5. nice thanks for the code.. help me a lot

    ReplyDelete
  6. However, MUCH more essential is the nature of your connections. The better quality your connections, the less you will require versus your opposition. https://800support.net/google-latest-news/8-tips-for-using-google-allo-app/

    ReplyDelete
  7. Thank you so much blog owener its really helpful for me the code ...

    http://www.customercare-email.com/gmail-help-number.html

    ReplyDelete
  8. Gmailify means you can simply protect your account from spam’s. With Gmailify you can simply manage your mail without non Gmail accounts.Gmailify

    ReplyDelete
  9. Thanks for such a great information and to provide us. We have the finest I mcafee certified technicians and If you're facing trouble in your mcafee antivirus software then just go through the link here. Click Here:- http://mcafeetechsupport.com/

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

    ReplyDelete
  11. Is it mandatory to have any licence from google to use this api for commercial purpose?

    ReplyDelete
  12. Hi,
    I am able to find the distance between to cities within the same country, But if am calculating distance between to country, its not working.
    Can any one suggest me to solve the problem.

    ReplyDelete
  13. Duration is not showing. It is showing null value. Can you please tell me the reason?

    ReplyDelete
  14. We are a team of talented professionals who are working 24*7 hours at Gmail customer service number +1(800) 674-2913 to bring future effective solutions at your Gmail solutions. Call at us and get solutions within defined timeline. Get more info and any query you can call us toll free number or visit at: http://www.gmailcustomerservicenumber.ca

    ReplyDelete
  15. Thank you for the Java code for distance calculation

    ReplyDelete
  16. Srinivas, how can I get more accurate distance calculation based on street level. currently with this code I am able to find distance using city level. Can you please help me on this.

    ReplyDelete
  17. Before you check out CBSE’s official website for the JEE Main 2019 online application form, remember that the National Testing Agency is the newly-formed authority to regulate the Joint Entrance Examination Main. Hence, you must visit the official web portal of NTA and fill in the online application form.

    ReplyDelete
  18. As the syllabus for CMAT exam is not released by the National Testing Agency, you will not find information about it on their official website. To help students know about the CMAT 2019 syllabus and prepare for the exam, we have provided below the CMAT 2019 syllabus based on the questions papers of previous year. You can plan your preparation for the exam based on this syllabus.

    ReplyDelete
  19. This is something that really bothers you, when you can send emails, but you are unable to receive emails in your own Yahoo! Mail inbox. Well, we have some quick fix for this concern. You can take help from these troubleshooting tips; yet, make sure to follow the order.

    ReplyDelete
  20. And once i just experienced onto your blog even when buying aspect to consider primarily a little tad submits. Fun strategy for potential, I'm sure bookmarking too gain categories final soars in place. distance calculator UK

    ReplyDelete
  21. You just want to approach to its third party experts by Dialing the McAfee tech support number +1 (888) 995-4664 Canada as it is open 24*7 hours for its customers. Or you can contact our website: https://www.mcafeetechnicalsupportnumber.com/

    ReplyDelete
  22. The world isn't level. Along these distance calculator UK lines, finding the distance between two points is in excess of a matter of illustration a straight line.

    ReplyDelete
  23. Our McAfee email support number is here 24*7 hours available for your help, so you can call us our support team any time and ask any type of query without hesitations. More info visit at: https://www.mcafeetechnicalsupportnumber.com/

    ReplyDelete
  24. I generated key from https://console.developers.google.com site ,
    while using that key i am getting below error, could you please help me in this


    Error:
    { "destination_addresses" : [], "error_message" : "This API project was not found. This API project may have been deleted.", "origin_addresses" : [], "rows" : [], "status" : "REQUEST_DENIED"}
    DistancePojo [status=REQUEST_DENIED, destination_addresses=[], origin_addresses=[], rows=[]]

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts