如何计算总距离和时间(getDistanceMatrix)

时间:2018-07-29 03:19:35

标签: javascript google-maps

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

我尝试的方式,只有我先进行计算,但我需要获取所有总和以显示给用户总距离

下面将图像附加到网络示例

SAMPLE IMAGE

我的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;

1 个答案:

答案 0 :(得分:0)

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";
}

proof of concept fiddle

screenshot of resulting map

代码段:

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"></script>
<div id="dvDistance"></div>
<div id="dvPanel"></div>
<div id="dvMap"></div>