Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - How to calculate total distance and time (getDistanceMatrix)

I need to get total distance and travel time with service.getDistanceMatrix({, sum A + B + C + D = total distance.

The way that i try, only i get the first calculate, but I need to get the sum alls points for show to user total-distance

The below attach the image with sample of web

SAMPLE IMAGE

My JavaScript code

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The DirectionsService returns all the information you need to calculate the total time and distance, you don't need to use the DistanceMatrix.

Per this related question: 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

code snippet:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...