Google maps 如何使用Google Maps API V3获取总行驶距离?

Google maps 如何使用Google Maps API V3获取总行驶距离?,google-maps,google-maps-api-3,driving-distance,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')

我以前能得到这样的结果:

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)
})
但看起来他们对我变了!看起来
trips
不再存在,而
routes
只会给你一堆腿。。。我真的需要遍历所有的腿并计算距离吗?

看看这里:

看起来你现在必须把每条腿的距离加起来

legs[]包含一个 方向腿对象,每个 包含有关某个分支的信息 路线,从两个位置 给定的路线。一条单独的腿就行了 在每个航路点或 指定的目的地。(A)有 任何航路点都不会包含一个航路点 方向支腿。)每条支腿由一个 一系列的方向步骤

根据:


下面是一个更完整的示例,使用。如果您不使用它,替换
flatBy
sum
应该不会太难

/**
 * 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));
            }
        });
    });
}
/**
*计算地址之间的总行驶距离。结果以米为单位。
*
*@param{string[]}地址字符串的地址数组。需要两个或更多。
*@returns{Promise}行驶距离(米)
*/
导出默认函数CalculateInstance(地址){
返回新承诺((解决、拒绝)=>{
如果(地址长度<2){
返回拒绝(新错误(`Distance calculation需要至少2次停止,获得${addresses.length}`));
}
const{TravelMode,directionservice,directionstatus}=google.maps;
const directionsService=新的directionsService;
常量origin=addresses.shift();
const destination=addresses.pop();
const waypoints=addresses.map(stop=>({location:stop}));
方向服务.路线({
起源,
航路点,
目的地,
travelMode:travelMode.DRIVING,
},(响应、状态)=>{
if(status==directionstatus.OK){
设distance=u.flatMap(response.routes,route=>_u.flatMap(route.legs,leg=>leg.distance.value));
返回解析(u.sum(距离));
}否则{
返回拒绝(新错误(状态));
}
});
});
}
请记住包括谷歌地图API:

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


另外,我很确定他们的ToS也要求你显示谷歌地图。

马克的答案是,
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');

简单地图
html,正文,#地图画布{
保证金:0;
填充:0;
身高:100%;
}
var方向显示;
var directionsService=new google.maps.directionsService();
var映射;
函数初始化(){
directionsDisplay=new google.maps.DirectionsRenderer();
var chicago=new google.maps.LatLng(26.912417,75.787288);
变量映射选项={
缩放:7,
mapTypeId:google.maps.mapTypeId.ROADMAP,
中心:芝加哥
}
map=new google.maps.map(document.getElementById(“地图画布”),mapOptions);
方向显示.setMap(地图);
}
函数calcRoute(){
var start=document.getElementById(“start”).value;
var end=document.getElementById(“end”).value;
var-waypts=[];
var checkboxArray=document.getElementById('waypoints');
对于(var i=0;i;
summaryPanel.innerHTML+=route.legs[i]。起始地址+'to';
summaryPanel.innerHTML+=route.legs[i]。结束地址+'
'; summaryPanel.innerHTML+=route.legs[i].duration.text+'
'; summaryPanel.innerHTML+=route.legs[i].distance.text+'

'; } } }); } google.maps.event.addDomListener(窗口“加载”,初始化); 开始: 斋浦尔 贾加特普拉 马尔维亚·纳加尔 锡卡 达乌萨 鲁尼亚瓦斯 卡罗利 巴兰 瑟瓦伊马托布尔 乌代布尔 比卡内尔 久鲁 结束: 斋浦尔 巴西 死亡 卡尼亚 鲁尼亚瓦斯 阿杰默 卡罗利 巴兰 瑟瓦伊马托布尔 乌代布尔 比卡内尔 久鲁 Tra的模式
var METERS_TO_MILES = 0.000621371192;
$('#distance').text((Math.round( totalDistance * METERS_TO_MILES * 10 ) / 10)+' miles');
$('#distance').text(Math.round( totalDuration / 60 )+' minutes');
<!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>
directionsDisplay.directions.routes[0].legs[0].distance.text
directionsDisplay.directions.routes[0].legs[0].duration.text