如何通过Google Maps API V3获得总驾驶距离?

时间:2010-07-15 00:27:35

标签: google-maps google-maps-api-3 driving-distance

我曾经能够像这样得到它:

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

但看起来他们改变了我their API!看起来trips已经不在了,routes只会给你一堆腿...我真的必须迭代所有的腿并总结一下距离吗?

5 个答案:

答案 0 :(得分:42)

根据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);

实际上,如果您没有任何航路点,这也可以正常工作:

$('#distance').text(directionsResult.routes[0].legs[0].distance.text);
$('#duration').text(directionsResult.routes[0].legs[0].duration.text);

以下是使用lodash的更全面的示例。如果您不使用flatBysum,则不应该太难替换。

/**
 * 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));
            }
        });
    });
}

请务必加入Google Maps API:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>

此外,我很确定他们的ToS也要求您显示Google地图。

答案 1 :(得分:12)

看看这里:

The Directions Results Object

看起来你现在必须总结每条腿的距离。

  

legs []包含一个数组   DirectionsLeg对象,每个对象   包含有关腿的信息   路线,从两个地方   给定的路线。一条单独的腿会   出现在每个航路点或   目的地指定。 (一条路线   没有航点只包含一个航点   DirectionsLeg。)每条腿由a组成   DirectionSteps系列。

答案 2 :(得分:7)

Mark的答案以totalDistance为单位,totalDuration为秒。

如果您在美国并希望获得具有单个小数点的里程,请按以下方式相乘:

var METERS_TO_MILES = 0.000621371192;
$('#distance').text((Math.round( totalDistance * METERS_TO_MILES * 10 ) / 10)+' miles');

如果你想要分钟:

$('#distance').text(Math.round( totalDuration / 60 )+' minutes');

答案 3 :(得分:3)

您可以轻松使用:

使用距离:

directionsDisplay.directions.routes[0].legs[0].distance.text

持续时间使用:

directionsDisplay.directions.routes[0].legs[0].duration.text

答案 4 :(得分:1)

<!DOCTYPE html>
<html>
<head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
        html, body, #map-canvas {
            margin: 0;
            padding: 0;
            height: 100%;
        }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>

        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var map;

        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var chicago = new google.maps.LatLng(26.912417, 75.787288);
            var mapOptions = {
                zoom: 7,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: chicago
            }
            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
            directionsDisplay.setMap(map);

        }

        function calcRoute() {
            var start = document.getElementById("start").value;
            var end = document.getElementById("end").value;


            var waypts = [];
            var checkboxArray = document.getElementById('waypoints');
            for(var i = 0; i < checkboxArray.length; i++) {
                if(checkboxArray.options[i].selected == true) {
                    waypts.push({
                        location: checkboxArray[i].value,
                        stopover: true
                    });
                }
            }


            var request = {
                origin: start,
                destination: end,
                waypoints: waypts,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function(response, status) {
                if(status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    var route = response.routes[0];
                    //  alert(route.legs[1].duration.text);
                    var summaryPanel = document.getElementById('directions_panel');
                    summaryPanel.innerHTML = '';
                    // For each route, display summary information.
                    for(var i = 0; i < route.legs.length; i++) {
                        var routeSegment = i + 1;
                        summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
                        summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
                        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
                        summaryPanel.innerHTML += route.legs[i].duration.text + '<br>';
                        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
                    }

                }
            });
        }

        google.maps.event.addDomListener(window, 'load', initialize);

    </script>
</head>
<body>
    <!--  <div id="map-canvas"></div>-->
    <div>
        <strong>Start: </strong>
        <select id="start" onChange="calcRoute();">
            <option value="Jaipur">Jaipur</option>
            <option value="jagatpura">jagatpura</option>
            <option value="malviya nagar, Jaipur">Malviya Nagar</option>
            <option value="khatu">Sikar</option>
            <option value="Dausa">Dausa</option>
            <option value="Luniawas">Luniyawas</option>
            <option value="Karoli">Karoli</option>
            <option value="Baran">Baran</option>
            <option value="Sawai Madhopur">Sawai Madhopur</option>
            <option value="Udaipur">Udaipur</option>
            <option value="Bikaner">Bikaner</option>
            <option value="Churu">Churu</option>
        </select>
        <strong>End: </strong>
        <select id="end" onChange="calcRoute();">
            <option value="Jaipur">Jaipur</option>
            <option value="bassi">bassi</option>
            <option value="goner">goner</option>
            <option value="Khaniya">Khaniya</option>
            <option value="Luniawas">Luniyawas</option>
            <option value="Ajmer">Ajmer</option>
            <option value="Karoli">Karoli</option>
            <option value="Baran">Baran</option>
            <option value="Sawai Madhopur">Sawai Madhopur</option>
            <option value="Udaipur">Udaipur</option>
            <option value="Bikaner">Bikaner</option>
            <option value="Churu">Churu</option>
        </select>
    </div>

    <div>
        <strong>Mode of Travel: </strong>
        <select id="mode" onChange="calcRoute();">
            <option value="DRIVING">Driving</option>
            <option value="WALKING">Walking</option>
            <option value="BICYCLING">Bicycling</option>
            <option value="TRANSIT">Transit</option>
        </select>

        <select multiple id="waypoints" onChange="calcRoute();">
            <option value="bassi">bassi</input>
            <option value="chainpura">chainpura</input>
            <option value="Kanauta">Kanauta</input>
        </select>

    </div>

    <div id="map-canvas" style="float:left;width:70%; height:40%"></div>

    <div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>

</body>
</html>