首页 > 解决方案 > 如何计算总距离和时间(getDistanceMatrix)

问题描述

我需要得到总距离和旅行时间service.getDistanceMatrix({,总和 A + B + C + D = 总距离。

我尝试的方式,只有我得到第一个计算,但我需要得到所有点的总和以显示给用户总距离

下面附上带有网络样本的图像

示例图像

我的 JavaScript 代码

var source, destination;
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        google.maps.event.addDomListener(window, 'load', function () {
            directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
        });
        // P1
        var stop;
        var markers = [];
        var waypts = [];
        var pardas = ["6.347033,-75.559017","6.348764,-75.562970","6.334624,-75.556157"];

        stop = new google.maps.LatLng(6.347033, -75.559017)
        waypts.push({
            location: stop,
            stopover: true
        });
        stop = new google.maps.LatLng(6.348764, -75.562970)
        waypts.push({
            location: stop,
            stopover: true
        });
            directionsDisplay = new google.maps.DirectionsRenderer({
                suppressMarkers: false,
            });

        window.onload=function(){
        function initialize() {
            //P2

        var mapOptions = {
                zoom: 15,
                //center: new google.maps.LatLng(6.3490548, -75.55802080000001),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
            }
         var map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById('dvPanel'));
            //calcRoute();
            }
            source = new google.maps.LatLng(6.3490548, -75.55802080000001);
            destination = new google.maps.LatLng(6.334624, -75.556157);         
            //P3

            function calcRoute() {

                for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
                }

                createMarker(source, 'source', false);
                createMarker(destination, 'destination', false);

            var route = response.routes[0];
            for (var i = 1; i < route['legs'].length; i++) {
            console.log(route['legs'][i].start_location.toString(), waypts[i - 1].location.toString());
            waypts[i - 1].location = route['legs'][i].start_location
            }

            for (var i = 0; i < waypts.length; i++) {
            createMarker(waypts[i].location, i, true);
                }
            }
            var request = {
                origin: source,
                destination: destination,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });

                var service = new google.maps.DistanceMatrixService();
                service.getDistanceMatrix({
                origins: [source],
                destinations: pardas,
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
                }, function (response, status) {
                if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
                    var distance = response.rows[0].elements[0].distance.text;
                    var duration = response.rows[0].elements[0].duration.text;
                    var dvDistance = document.getElementById("dvDistance");
                    dvDistance.innerHTML = "";
                    dvDistance.innerHTML += "Distance: " + distance + "<br />";
                    dvDistance.innerHTML += "Duration:" + duration;

标签: javascriptgoogle-maps

解决方案


DirectionsService 返回计算总时间和距离所需的所有信息,您不需要使用 DistanceMatrix。

根据这个相关问题:Google Maps API: Total distance with waypoints

function computeTotalDistance(result) {
  var totalDist = 0;
  var totalTime = 0;
  var myroute = result.routes[0];
  for (i = 0; i < myroute.legs.length; i++) {
    totalDist += myroute.legs[i].distance.value;
    totalTime += myroute.legs[i].duration.value;
  }
  totalDist = totalDist / 1000.
  document.getElementById("dvDistance").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}

概念证明小提琴

结果地图的屏幕截图

代码片段:

var source, destination;
var directionsService = new google.maps.DirectionsService();
var stop;
var markers = [];
var waypts = [];

stop = new google.maps.LatLng(6.347033, -75.559017)
waypts.push({
  location: stop,
  stopover: true
});
stop = new google.maps.LatLng(6.348764, -75.562970)
waypts.push({
  location: stop,
  stopover: true
});
var directionsDisplay = new google.maps.DirectionsRenderer({
  suppressMarkers: false,
});

window.onload = function() {
  var mapOptions = {
    zoom: 15,
    //center: new google.maps.LatLng(6.3490548, -75.55802080000001),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  }
  var map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('dvPanel'));

  source = new google.maps.LatLng(6.3490548, -75.55802080000001);
  destination = new google.maps.LatLng(6.334624, -75.556157);

  var request = {
    origin: source,
    destination: destination,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      computeTotalDistance(response);
    }
  });
}

function computeTotalDistance(result) {
  var totalDist = 0;
  var totalTime = 0;
  var myroute = result.routes[0];
  for (i = 0; i < myroute.legs.length; i++) {
    totalDist += myroute.legs[i].distance.value;
    totalTime += myroute.legs[i].duration.value;
  }
  totalDist = totalDist / 1000.
  document.getElementById("dvDistance").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

#dvMap {
  height: 100%;
  width: 50%;
  margin: 0px;
  padding: 0px;
}

#dvPanel {
  height: 100%;
  width: 50%;
  margin: 0px;
  padding: 0px;
  float: right;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="dvDistance"></div>
<div id="dvPanel"></div>
<div id="dvMap"></div>


推荐阅读