如何计算总距离和时间(getDistanceMatrix) [英] How to calculate total distance and time (getDistanceMatrix)

查看:67
本文介绍了如何计算总距离和时间(getDistanceMatrix)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 service.getDistanceMatrix({,sum A + B + C + D =总距离.

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

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

代码段:

  var源,目标;vardirectionService =新的google.maps.DirectionsService();var stop;var markers = [];var waypts = [];停止=新的google.maps.LatLng(6.347033,-75.559017)waypts.push({位置:停止,中途停留:true});停止=新的google.maps.LatLng(6.348764,-75.562970)waypts.push({位置:停止,中途停留:true});var DirectionsDisplay = new google.maps.DirectionsRenderer({inhibitorMarkers:否,});window.onload = function(){var mapOptions = {变焦:15//center:新的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'));来源=新的google.maps.LatLng(6.3490548,-75.55802080000001);destination = new google.maps.LatLng(6.334624,-75.556157);var request = {来源:来源,目的地:目的地,航路点:航路点,optimizeWaypoints:正确,travelMode:google.maps.TravelMode.DRIVING};directionService.route(请求,功能(响应,状态){如果(状态== google.maps.DirectionsStatus.OK){directionsDisplay.setDirections(response);computeTotalDistance(response);}});}函数computeTotalDistance(result){var totalDist = 0;var totalTime = 0;var myroute = result.routes [0];对于(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 =总距离为:" + totalDist +"km总时间为:" +(totalTime/60).toFixed(2)+分钟";}  

  html,身体 {高度:100%;宽度:100%;边距:0px;填充:0px;}#dvMap {高度:100%;宽度:50%;边距:0px;填充:0px;}#dvPanel {高度:100%;宽度:50%;边距:0px;填充:0px;浮动:正确;}  

 <脚本src ="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">< lt;/script>< div id ="dvDistance"></div>< div id ="dvPanel"></div>< div id ="dvMap"></div>  

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;

解决方案

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

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>

这篇关于如何计算总距离和时间(getDistanceMatrix)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆