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

tsaebeht picture tsaebeht · Nov 12, 2016 · Viewed 14.4k times · Source

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

Answer

MK-rou picture MK-rou · Mar 28, 2017

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"
}