28

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

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

但看起来他们改变了我的 API!看起来trips已经不存在了,routes只给你一堆腿……我现在真的要遍历所有腿并总结距离吗?

4

5 回答 5

48

根据莱尼尔的回答

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>

另外,我很确定他们的服务条款也要求您显示 Google 地图。

于 2010-07-15T00:44:10.563 回答
12

看看这里:

方向结果对象

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

legs[] 包含一个 DirectionsLeg 对象数组,每个对象都包含来自给定路线中两个位置的路线段的信息。每个指定的航路点或目的地都有一个单独的航段。(没有航路点的路线将只包含一个 DirectionsLeg。)每条线路由一系列 DirectionSteps 组成。

于 2010-07-15T00:34:24.877 回答
7

马克的回答是以米为单位,以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');
于 2011-11-30T22:09:01.780 回答
5

您可以通过使用轻松获得:

使用距离:

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

使用持续时间:

directionsDisplay.directions.routes[0].legs[0].duration.text
于 2015-04-25T09:05:53.297 回答
2
<!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>
于 2013-06-13T04:53:55.197 回答