How do we get the shortest distance route from point A to B by default from Google Direction API suggested alternative routes? By default it gives us shortest duration routes depending upon the current traffic conditions. I have noticed that google responds with multiple alternative routes if you turn on "provideRouteAlternatives=true", I was wondering if we could send a parameter to Google API so that it will always return shortest distance route by default
As Rameshwor has mentioned, the suggested route returned by Google may be optimised for journey time rather than journey distance. If one or more waypoints have been specified then only one route may be returned anyway, but programatically it's best to assume that more than one route will always be returned.
The following example shows a simple way to find the route with the shortest journey distance using jQuery; please note this code isn't optimised but it should work:
var route_options = [];
for (var i = 0; i < response.routes.length; i++)
{
var route = response.routes[i];
var distance = 0;
// Total the legs to find the overall journey distance for each route option
for (var j = 0; j < route.legs.length; j++)
{
distance += route.legs[j].distance.value; // metres
}
route_options.push({
'route_id': i,
'distance': distance
});
}
/*
route_options = [
{route_id:0, distance:35125},
{route_id:1, distance:22918},
{route_id:2, distance:20561}
];
*/
// Sort the route options; shortest to longest distance in ascending order
route_options.sort(function(a, b) {
return parseInt(a.distance) - parseInt(b.distance);
});
/*
route_options = [
{route_id:2, distance:20561},
{route_id:1, distance:22918},
{route_id:0, distance:35125}
];
*/
var shortest_distance = (route_options[0]['distance'] * 0.001); // convert metres to kilometres
You can then access the "route_id" value to access the correct route in the response object.