Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Google Maps Distance Matrix JAVA API to obtain closest distance between source and multiple destinations

I have added the dependency of Google Maps API Java Client in my Java project. I have a set of origin distances, destination distance and also teh GeoApiContext as such:

GeoApiContext context = new GeoApiContext().setApiKey(MY_API_KEY);
String[] destinationAddress = {"40.7127837,-74.0059413", "33.9533487,-117.3961564", "38.6270025,-90.19940419999999"};
String[] originAddress = {"12.8445,80.1523"};

I want to get the (Airplane?) Distances between these points. I know we can send a simple HTTP request like
https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.690515%73.6334271&key=YOUR_API_KEY
But I want to use the JAVA Google Maps API. I have tried to do DistanceMatrixApiRequest s = DistanceMatrixApi.getDistanceMatrix(context, originAddress, destinationAddress); but there is no getArrivalTimes or getDistanceMatrix or anyway to send request. I am very confused. Plz help. Thanks

like image 813
tsaebeht Avatar asked Nov 12 '16 09:11

tsaebeht


2 Answers

Try this :

private static final String API_KEY = "YOUR_API_KEY";
private static final GeoApiContext context = new GeoApiContext().setApiKey(API_KEY);


public DistanceMatrix estimateRouteTime(DateTime time, Boolean isForCalculateArrivalTime, DirectionsApi.RouteRestriction routeRestriction, LatLng departure, LatLng... arrivals) {
    try {
        DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(context);
        if (isForCalculateArrivalTime) {
            req.departureTime(time);
        } else {
            req.arrivalTime(time);
        }
        if (routeRestriction == null) {
            routeRestriction = DirectionsApi.RouteRestriction.TOLLS;
        }
        DistanceMatrix trix = req.origins(departure)
                .destinations(arrivals)
                .mode(TravelMode.DRIVING)
                .avoid(routeRestriction)
                .language("fr-FR")
                .await();
        return trix;

    } catch (ApiException e) {
        System.out.println(e.getMessage());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return null;
}

The DistanceMatrix response object is like that :

{
   "destination_addresses" : [ "San Francisco, Californie, États-Unis" ],
   "origin_addresses" : [ "Seattle, Washington, États-Unis" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1 300 km",
                  "value" : 1299878
               },
               "duration" : {
                  "text" : "12 heures 32 minutes",
                  "value" : 45146
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
like image 182
MK-rou Avatar answered Oct 12 '22 23:10

MK-rou


Well this is a complete answer of how to calculate distance and time with google distance matrix api between two places. If you are not using maven then you have to set these jars in your classpath

pom.xml

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/com.squareup.okio/okio -->
<dependency>
    <groupId>com.squareup.okio</groupId>
    <artifactId>okio</artifactId>
    <version>1.12.0</version>
</dependency>
  <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client -->
<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
</dependency>

This is a class to send http request and get the data in json format

 package google.distance.api;

import java.io.IOException;

import org.springframework.stereotype.Component;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Component
public class DistanceTime {



    private static final String API_KEY="YOUR KEY";
    OkHttpClient client = new OkHttpClient();


public String calculate(String source ,String destination) throws IOException {
String url="https://maps.googleapis.com/maps/api/distancematrix/json?origins="+source+"&destinations="+destination+"&key="+ API_KEY;
            Request request = new Request.Builder()
                .url(url)
                .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
          }


}

As I am using Spring ,so here is my Controller method to get the data

private DistanceTime distance;

     @Autowired
    public void setDistance(DistanceTime distance) {
    this.distance = distance;
}


    public ModelAndView Api(@RequestParam("picking_up") String source,@RequestParam("dropping_off") String destination,@RequestParam("pick_up_date") String time) {
            try {
                  //method of DistanceTime Class
                String response=distance.calculate(source,destination);

            System.out.println(response);
            }

            catch(Exception e) {
                System.out.println("Exception Occurred");
            }

            return new ModelAndView("home");

        }  

Now the Tough Part was iterating over JSON data to get the distance and time In the above method I was getting json data in variable response ,so here is the code to extract distance and time from it The response was something Like

{
   "destination_addresses" : [
      "Private"
   ],
   "origin_addresses" : [ "Private" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,052 km",
                  "value" : 1051911
               },
               "duration" : {
                  "text" : "17 hours 10 mins",
                  "value" : 61785
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}



 JSONParser parser = new JSONParser();
        try {

         Object obj = parser.parse(response);
         JSONObject jsonobj=(JSONObject)obj;

         JSONArray dist=(JSONArray)jsonobj.get("rows");
         JSONObject obj2 = (JSONObject)dist.get(0);
         JSONArray disting=(JSONArray)obj2.get("elements");
         JSONObject obj3 = (JSONObject)disting.get(0);
         JSONObject obj4=(JSONObject)obj3.get("distance");
         JSONObject obj5=(JSONObject)obj3.get("duration");
         System.out.println(obj4.get("text"));
         System.out.println(obj5.get("text"));

    }
catch(Exception e) {
    e.printStackTrace();
}
like image 20
Shubh Avatar answered Oct 13 '22 01:10

Shubh