Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get total driving distance with Google Maps API V3?

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?

like image 914
mpen Avatar asked Jul 15 '10 00:07

mpen


People also ask

How do I Measure distance on Google Maps API?

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.

Can you Measure road distance on Google Maps?

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).

Is Google Distance Matrix API free?

The Distance Matrix API uses a pay-as-you-go pricing model.


1 Answers

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.

like image 194
mpen Avatar answered Sep 28 '22 17:09

mpen