Search code examples
javagoogle-mapsroutesdirectionsgoogle-directions-api

How to optimise route in google map using Google map client java api.


I am getting route details for list of latitude and longitudes like this,

DirectionsRoute[] routes = DirectionsApi.newRequest(context)
                .mode(TravelMode).origin(startPoint).destination(endPoint)
                .waypoints(wayPoints).await();

But the routes that i am getting are not optimised so i want to optimise route by using google java client api.

In google map javascript api we can optimise by giving boolean attribute like this

 {
  origin: LatLng | String | google.maps.Place,
  destination: LatLng | String | google.maps.Place,
  travelMode: TravelMode,
  drivingOptions: DrivingOptions,
  waypoints[]: DirectionsWaypoint,
  optimizeWaypoints: boolean
}

But how to achieve this using Google maps java client api?


Solution

  • You can use the optimizeWaypoints method. Make sure that you use the latest (0.1.16) version of google-maps-services:

    dependencies {
        compile 'com.google.maps:google-maps-services:0.1.16'
    }
    
    <dependency>
        <groupId>com.google.maps</groupId>
        <artifactId>google-maps-services</artifactId>
        <version>0.1.16</version>
    </dependency>
    

    In your code:

    DirectionsRoute[] routes = DirectionsApi.newRequest(context)
        .mode(TravelMode)
        .origin(startPoint)
        .destination(endPoint)
        .waypoints(wayPoints)
        .optimizeWaypoints(true) // Add this
        .await();