As Rameshwor mentioned, the proposed route returned by Google can be optimized for travel time rather than travel distance. If one or more waypoints are specified, only one route can be returned in any case, but it is better to assume in software that more than one route will always be returned.
The following example shows an easy way to find the route with the shortest distance using jQuery; note that this code is not optimized, 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 value of โroute_idโ to access the correct route in the response object.
source share