tags:

views:

47

answers:

2

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?

+1  A: 

Take a look here:

The Directions Results Object

It looks like you now have to sum up each leg distance.

legs[] contains an array of DirectionsLeg objects, each of which contains information about a leg of the route, from two locations within the given route. A separate leg will be present for each waypoint or destination specified. (A route with no waypoints will contain exactly one DirectionsLeg.) Each leg consists of a series of DirectionSteps.

Leniel Macaferi
So...exactly what I said! Although I was misinformed about what a "leg" was. Thought it was what they call a "step". Iterating over 1 leg isn't that bad then.
Mark
+2  A: 

As per Leniel's answer:

    var totalDistance = 0;
    var totalDuration = 0;
    var legs = directionsResult.routes[0].legs;
    for(i in legs) {
        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);
Mark