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?
By first extracting the data from our user's address and then creating a function we'll be able to calculate the distances in kilometers from one point to another.
Select Measure distance. To create a path to measure, click anywhere on the map. To add another point, click anywhere on the map. At the bottom, you can find the total distance in miles (mi) and kilometers (km).
The Distance Matrix API uses a pay-as-you-go pricing model.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With