【问题标题】:How to get total driving distance with Google Maps API V3?如何使用 Google Maps API V3 获得总行驶距离?
【发布时间】:2011-03-16 03:53:34
【问题描述】:

我以前是这样弄的:

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 只给了你一堆腿……我现在真的要遍历所有腿并总结距离吗?

【问题讨论】:

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


    【解决方案1】:

    根据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 地图。

    【讨论】:

      【解决方案2】:

      看这里:

      The Directions Results Object

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

      legs[] 包含一个数组 DirectionsLeg 对象,其中每个 包含有关一条腿的信息 路线,从内部的两个位置 给定的路线。一条单独的腿将 出现在每个航路点或 指定的目的地。 (一条路线与 没有航点将包含一个 DirectionsLeg.) 每条腿由一个 一系列 DirectionSteps。

      【讨论】:

      • 所以...正是我所说的!虽然我被误解了什么是“腿”。认为这是他们所谓的“一步”。迭代超过 1 条腿并没有那么糟糕。
      【解决方案3】:

      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');
      

      【讨论】:

        【解决方案4】:

        你可以很容易地使用:

        使用距离:

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

        使用时长:

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

        【讨论】:

        • 仅当您有 1 条腿时。从 A 点到 B。对于多条腿,您必须根据上面的@mpen 答案对腿值求和,并转换距离的米数和 duration.value 的秒数
        【解决方案5】:
        <!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>
        

        【讨论】:

          猜你喜欢
          • 2017-04-09
          • 1970-01-01
          • 2015-05-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多