Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As per <a href="https://stackoverflow.com/a/3251638/65387">Leniel's answer</a>:</p> <pre><code>var totalDistance = 0; var totalDuration = 0; var legs = directionsResult.routes[0].legs; for(var i=0; i&lt;legs.length; ++i) { totalDistance += legs[i].distance.value; totalDuration += legs[i].duration.value; } $('#distance').text(totalDistance); $('#duration').text(totalDuration); </code></pre> <p>Actually, this works just fine too, if you don't have any waypoints:</p> <pre><code>$('#distance').text(directionsResult.routes[0].legs[0].distance.text); $('#duration').text(directionsResult.routes[0].legs[0].duration.text); </code></pre> <hr> <p>Here's a fuller example using <a href="https://lodash.com/docs/4.17.4#flatMap" rel="noreferrer">lodash</a>. Shouldn't be too hard to replace <code>flatBy</code> and <code>sum</code> if you're not using it.</p> <pre><code>/** * 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) =&gt; { if(addresses.length &lt; 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 =&gt; ({location: stop})); directionsService.route({ origin, waypoints, destination, travelMode: TravelMode.DRIVING, }, (response, status) =&gt; { if(status === DirectionsStatus.OK) { let distances = _.flatMap(response.routes, route =&gt; _.flatMap(route.legs, leg =&gt; leg.distance.value)); return resolve(_.sum(distances)); } else { return reject(new Error(status)); } }); }); } </code></pre> <p>Remember to include the Google Maps API:</p> <pre><code>&lt;script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&amp;libraries=places"&gt;&lt;/script&gt; </code></pre> <p>Also, I'm pretty sure their ToS require you to display a Google Map too.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload