I used to be able to get it like this:
directionsService.route(directionsRequest, function(directionsResult, directionsStatus) {
var directionsRenderer = new google.maps.DirectionsRenderer({
directions: directionsResult,
map: map
});
$('#distance').text(directionsResult.trips[0].routes[0].distance.text)
$('#duration').text(directionsResult.trips[0].routes[0].duration.text)
})
But it looks like they changed their API on me! Looks like trips
is no longer there, and routes
only gives you a bunch of legs... do I really have to iterate over all the legs and sum up the distance now?
As per Leniel's answer:
var totalDistance = 0;
var totalDuration = 0;
var legs = directionsResult.routes[0].legs;
for(var i=0; i<legs.length; ++i) {
totalDistance += legs[i].distance.value;
totalDuration += legs[i].duration.value;
}
$('#distance').text(totalDistance);
$('#duration').text(totalDuration);
Actually, this works just fine too, if you don't have any waypoints:
$('#distance').text(directionsResult.routes[0].legs[0].distance.text);
$('#duration').text(directionsResult.routes[0].legs[0].duration.text);
Here's a fuller example using lodash. Shouldn't be too hard to replace flatBy
and sum
if you're not using it.
/**
* Computes the total driving distance between addresses. Result in meters.
*
* @param {string[]} addresses Array of address strings. Requires two or more.
* @returns {Promise} Driving distance in meters
*/
export default function calculateDistance(addresses) {
return new Promise((resolve, reject) => {
if(addresses.length < 2) {
return reject(new Error(`Distance calculation requires at least 2 stops, got ${addresses.length}`));
}
const {TravelMode, DirectionsService, DirectionsStatus} = google.maps;
const directionsService = new DirectionsService;
const origin = addresses.shift();
const destination = addresses.pop();
const waypoints = addresses.map(stop => ({location: stop}));
directionsService.route({
origin,
waypoints,
destination,
travelMode: TravelMode.DRIVING,
}, (response, status) => {
if(status === DirectionsStatus.OK) {
let distances = _.flatMap(response.routes, route => _.flatMap(route.legs, leg => leg.distance.value));
return resolve(_.sum(distances));
} else {
return reject(new Error(status));
}
});
});
}
Remember to include the Google Maps API:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
Also, I'm pretty sure their ToS require you to display a Google Map too.