Google地图设置航点可以节省时间

时间:2015-08-11 10:41:10

标签: javascript google-maps time calculator

帮我解决这个案子 - 演示:http://jsfiddle.net/aLosek26/(html中的解释)

如何根据最后一个地址的预设到达时间计算每个站点的接送时间?

这是代码

    <style>
        html {
            height: 100%
        }
        body {
            height: 100%;
            margin: 0px;
            padding: 0px
        }
        .ziel {
            padding: 10px;
            background-color: #0086A9;
            color: #fff;
            font-size: 15px;
            margin-bottom: 10px;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maps.google.com/maps/api/js"></script>
    <div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
    <div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
        <div id="directions_panel" style="margin:20px;background-color:#FFEE77;font-family:Gotham, 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:12px;padding:20px;"></div>
        <div style="padding-left:10px;">I want "pick up time" to look like this:
            <br> A to B -> pick up time: 13:12
            <br> B to C -> pick up time: 13:16
            <br> C to D -> pick up time: 13:48
            <br> D to E -> pick up time: 14:20
            <br> E to F -> pick up time: 14:32
            <br> F to G -> pick up time: 14:45
            <br>
            <br> </div>
        <div><strong>Arrival to the last address is   15:00 </strong> </div>
        <br>
        <br>
        <br>
        <div id="total"></div>
    </div>
    <script>
        var directionDisplay;
        var directionsService = new google.maps.DirectionsService();
        var map;

        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var chicago = new google.maps.LatLng(41.850033, -87.6500523);
            var myOptions = {
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: chicago
            }
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            directionsDisplay.setMap(map);
            calcRoute();
        }
        google.maps.event.addDomListener(window, 'load', initialize);

        function calcRoute() {
            var checkboxArray = ["Klosterneuburgerstrasse 3,1200 Wien", "Simon-Denk Gasse 2,1090 wien", "Favoritenstrasse 3, 1100 Wien", "Hütteldorferstrasse 4, 1140 Wien", "Summeringerhauptstrasse 3, 1110 Wien", "Kobesgase, 1220 Wien", "Ziegelhofstrasse 3, 1220 Wien"];
            var start = checkboxArray[0];
            var end = checkboxArray[checkboxArray.length - 1];
            var waypts = [];
            for(var i = 1; i < checkboxArray.length - 1; i++) {
                var adresanesto = checkboxArray[i];
                if(adresanesto !== "") {
                    waypts.push({
                        location: adresanesto,
                        stopover: true
                    });
                }
            }
            var request = {
                // from: Blackpool to: Preston to: Blackburn
                origin: start,
                destination: end,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(request, function(response, status) {
                if(status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    var route = response.routes[0];
                    var summaryPanel = document.getElementById("directions_panel");
                    summaryPanel.innerHTML = "";
                    // For each route, display summary information.
                    var ankunft = "06:00";
                    for(var i = 0; i < route.legs.length; i++) {
                        var hms = ankunft; // your input string
                        var zeit = route.legs[i].duration.value;
                        var zeitx = (zeit / 60).toFixed(0);
                        var a = hms.split(':');
                        var sekunde = (+a[0]) * 60 * 60 + (+a[1]) * 60;
                        var min5x = zeitx * 60;
                        var sec_num = (+sekunde - +min5x);
                        var hours = Math.floor(sec_num / 3600);
                        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
                        var seconds = Math.floor(sec_num - (hours * 3600) - (minutes * 60));
                        if(hours < 10) {
                            hours = "0" + hours;
                        }
                        if(minutes < 10) {
                            minutes = "0" + minutes;
                        }
                        if(seconds < 10) {
                            seconds = "0" + seconds;
                        }
                        var vreme = hours + ':' + minutes;
                        var routeSegment = i + 1;
                        var ruta = "ruta" + routeSegment;
                        var timespan = "timespan" + routeSegment;
                        var vremespan = "vremespan" + routeSegment;
                        if(routeSegment == 1) {
                            var ziel = 'A to B';
                        }
                        if(routeSegment == 2) {
                            var ziel = 'B to C';
                        }
                        if(routeSegment == 3) {
                            var ziel = 'C to D';
                        }
                        if(routeSegment == 4) {
                            var ziel = 'D to E';
                        }
                        if(routeSegment == 5) {
                            var ziel = 'E to F';
                        }
                        if(routeSegment == 6) {
                            var ziel = 'F to G';
                        }
                        if(routeSegment == 7) {
                            var ziel = 'G to H';
                        }
                        if(routeSegment == 8) {
                            var ziel = 'H to I';
                        }
                        summaryPanel.innerHTML += "<div id='" + ruta + "'><b><span class='ziel'> " + ziel + "</span></b><br /><br />";
                        // summaryPanel.innerHTML += route.legs[i].start_address + " to ";
                        // summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
                        summaryPanel.innerHTML += "<b>Distance: </b>" + route.legs[i].distance.text + "<br />";
                        summaryPanel.innerHTML += "<b>Duration: </b><span id='" + timespan + "'>" + zeitx + "</span> Min.<br />";
                        summaryPanel.innerHTML += "<b>Pick up time: </b><span id='" + vremespan + "'><span style='color:#ff0000'>" + vreme + "</span> <----  ???<br /><br /></div>";
                    }
                    computeTotalDistance(response);
                } else {
                    alert("directions response " + status);
                }
            });
        }

        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("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(0) + " minutes";
        }
    </script>

EDIT 解释

我们有一个起始地址和结束地址以及四个航路点并且具有变量“到达” - 到达时间

到达15:00

A B C D E F G =不同的地址 - 街道号码邮政编码城市......

A to B   Distance: 1,2 km   Duration: 4 Min.
B to C   Distance: 13,8 km  Duration: 32 Min.
C to D   Distance: 20,3 km  Duration: 32 Min.
D to E   Distance: 6,9 km   Duration: 12 Min.
E to F   Distance: 9,1 km   Duration: 13 Min.
F to G   Distance: 6,9 km   Duration: 15 Min.

A是起始地址 B C D E和F是航路点 G是结束地址

示例:

结束地址的到达时间设置为15:00,航路点F和结束地址G之间的持续时间为15分钟,然后是航点F的接收时间为14:45 | F到G的接送时间为14:45

如何计算所有航点?

A到B接送时间?

B到C接送时间?

...

我想看起来像这样

A到B - 距离:1,2 km持续时间:4分钟接送时间:13:12

B to C - 距离:13,8 km时长:32分钟接送时间:13:16

C到D - 距离:20,3 km持续时间:32分钟接机时间:13:48

D to E - 距离:6,9 km持续时间:12分钟接送时间:14:20

E到F - 距离:9,1 km持续时间:13分钟接送时间:14:32

F到G - 距离:6,9 km持续时间:15分钟接送时间:14:45

我需要这辆出租车

我希望你明白我的意思......

抱歉我的英语不好......

2 个答案:

答案 0 :(得分:0)

当你不知道下一段腿的持续时间时,你将如何计算航点的起飞时间?

你必须从最后一条腿到第一条腿进行迭代 而不是使用复杂的时间计算,你应该使用Date - 对象,这是它的好处。

&#13;
&#13;
function initialize() {
  var goo = google.maps,
    map = new goo.Map(document.getElementById("map_canvas"), {
      center: new goo.LatLng(41.850033, -87.6500523),
      zoom: 6,
      noClear: true,
      disableDefaultUI: true
    }),
    service = new goo.DirectionsService(),
    renderer = new goo.DirectionsRenderer({
      map: map
    });
  map.controls[goo.ControlPosition.TOP_RIGHT]
    .push(document.getElementById("directions_panel"));
  goo.event
    .addDomListener(document.getElementById("directions_panel"),
      'click',
      function(e) {
        var legs = this.querySelectorAll('div[id^="ruta"][data-latlng]');
        for (var i = 0; i < legs.length; ++i) {
          if (
            legs[i] == e.target ||
            legs[i].contains(e.target)
          ) {
            var latlng = legs[i]
              .getAttribute('data-latlng')
              .split(',')
            map.panTo(new goo.LatLng(latlng[0], latlng[1]));
            return;
          }
        }
      });
  calcRoute(service,
    renderer, ["Klosterneuburgerstrasse 3,1200 Wien",
      "Simon-Denk Gasse 2,1090 wien",
      "Favoritenstrasse 3, 1100 Wien",
      "Hütteldorferstrasse 4, 1140 Wien",
      "Summeringerhauptstrasse 3, 1110 Wien",
      "Kobesgase, 1220 Wien",
      "Ziegelhofstrasse 3, 1220 Wien"
    ]);
}

function calcRoute(service, renderer, route) {
  var goo = google.maps,
    request = {
      origin: route.shift(),
      destination: route.pop(),
      waypoints: (function(r) {
        var a = [];
        for (var i = 0; i < r.length; ++i) {
          a.push({
            location: r[i],
            stopover: true
          })
        }
        return a;
      }(route)),
      optimizeWaypoints: true,
      travelMode: goo.DirectionsTravelMode.DRIVING
    };

  service.route(request, function(response, status) {
    if (status == goo.DirectionsStatus.OK) {
      renderer.setDirections(response);
      var route = response.routes[0];

      //parse string into a Date-object
      var arrival = (function(hm) {
          var d = new Date(),
            a = hm.split(':');
          d.setHours(parseInt(a[0]));
          d.setMinutes(parseInt(a[1]));
          d.setSeconds(0);
          return d;
        }("06:00")),
        total = {
          duration: 0,
          distance: 0
        },
        //returns the formatted pickup-time

        pickup = function(duration) {
          arrival.setTime(arrival.getTime() - (duration * 1000));

          return ([("0" + arrival.getHours()).slice(-2), 
                   ("0" + arrival.getMinutes()).slice(-2)]
            .join(':'));
        },
        html = [],
        item;

      for (var i = route.legs.length - 1; i >= 0; --i) {
        total.distance += route.legs[i].distance.value;
        total.duration += route.legs[i].duration.value;

        item = "<div data-latlng='" + 
                  route.legs[i].start_location.toUrlValue() + "' id='ruta" + 
                 (i + 1) + "'><b><span class='ziel'> " +
                 String.fromCharCode(65 + i) +
                 ' to ' +
                 String.fromCharCode(65 + 1 + i) +
                 "</span></b><br /><br />";

        item += "<b>Distance: </b>" + route.legs[i].distance.text + "<br />";
        item += "<b>Duration: </b><span id='timespan" + (i + 1) + "'>" +
          (route.legs[i].duration.value / 60).toFixed(0) +
          "</span> Min.<br />";
        item += "<b>Pick up time: </b><span id='vremespan" + (i + 1) + "'>" +
          "<span style='color:#ff0000'>" +
          pickup(route.legs[i].duration.value) + "</span><br /><br /></div>";
        html.unshift(item);
      }

      html.push(
        "<hr/>total distance is: " + (total.distance / 1000).toFixed(1) +
        " km<br>total time is: " +
        (total.duration / 60).toFixed(0) + " minutes")+'<br/><hr/>';
      document.getElementById("directions_panel").innerHTML = html.join('');

    } else {
      document.getElementById("directions_panel") = "directions response:" + status;
    }
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html,
body,
#map_canvas {
  height: 100%;
  margin: 0px;
  padding: 0px
}
.ziel {
  padding: 5px;
  background-color: #0086A9;
  color: #fff;
  font-size: 1.1em;
  margin-bottom: 10px;
  cursor: pointer;
}
#directions_panel {
  height:60%;
  overflow: auto;
  background-color: #FFEE77;
  font-size: 12px;
  padding: 5px 5px 50px 5px;
}
&#13;
<script src="http://maps.google.com/maps/api/js?v=3"></script>
<div id="map_canvas">
  <div id="directions_panel"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为我和Dr.Molle完全一样(我们开始同时编写这段代码)。我也从完成开始迭代。

但我想发布我的代码。

我会在几秒钟内完成计算。只在最后一刻转换;并且不使用自定义计算,例如(小时* 3600)...时间很棘手;你想不到很多例外。

<style>
    html {
        height: 100%
    }
    body {
        height: 100%;
        margin: 0px;
        padding: 0px
    }
    .ziel {
        padding: 10px;
        background-color: #0086A9;
        color: #fff;
        font-size: 15px;
        margin-bottom: 10px;
    }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
    <div id="directions_panel" style="margin:20px;background-color:#FFEE77;font-family:Gotham, 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:12px;padding:20px;"></div>
    <div style="padding-left:10px;">I want "pick up time" to look like this:
        <br> A to B -> pick up time: 13:12
        <br> B to C -> pick up time: 13:16
        <br> C to D -> pick up time: 13:48
        <br> D to E -> pick up time: 14:20
        <br> E to F -> pick up time: 14:32
        <br> F to G -> pick up time: 14:45
        <br>
        <br> </div>
    <div><strong>Arrival to the last address is   15:00 </strong> </div>
    <br>
    <br>
    <br>
    <div id="total"></div>
</div>
<script>
    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;

    function initialize() {
        directionsDisplay = new google.maps.DirectionsRenderer();
        var chicago = new google.maps.LatLng(41.850033, -87.6500523);
        var myOptions = {
            zoom: 6,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: chicago
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        directionsDisplay.setMap(map);
        calcRoute();
    }
    google.maps.event.addDomListener(window, 'load', initialize);

    function calcRoute() {
        var checkboxArray = ["Klosterneuburgerstrasse 3,1200 Wien", "Simon-Denk Gasse 2,1090 wien", "Favoritenstrasse 3, 1100 Wien", "Hütteldorferstrasse 4, 1140 Wien", "Summeringerhauptstrasse 3, 1110 Wien", "Kobesgase, 1220 Wien", "Ziegelhofstrasse 3, 1220 Wien"];
        var start = checkboxArray[0];
        var end = checkboxArray[checkboxArray.length - 1];
        var waypts = [];
        for(var i = 1; i < checkboxArray.length - 1; i++) {
            var adresanesto = checkboxArray[i];
            if(adresanesto !== "") {
                waypts.push({
                    location: adresanesto,
                    stopover: true
                });
            }
        }
        var request = {
            // from: Blackpool to: Preston to: Blackburn
            origin: start,
            destination: end,
            waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
            if(status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                var route = response.routes[0];
                var summaryPanel = document.getElementById("directions_panel");
                summaryPanel.innerHTML = "";
                // For each route, display summary information.

                var displayText = '';
                var arrival = new Date(); 

                var secondsToArrival = 0;
                // set arrival time
                arrival.setHours(15);
                arrival.setMinutes(0);
                arrival.setSeconds(0);

                // let's calculate back.  From finish to start
                for(var i = route.legs.length - 1; i >=0; i--) {
                  //summaryPanel.innerHTML +=  +'s<br>';
                  secondsToArrival += route.legs[i].duration.value;
                  // new date variable.
                  var startAtWaypoint = new Date(); 
                  startAtWaypoint.setHours(arrival.getHours());
                  startAtWaypoint.setMinutes(arrival.getMinutes());
                  startAtWaypoint.setSeconds(arrival.getSeconds());

                  // calculate difference.  We subtract the seconds.
                  startAtWaypoint.setSeconds(arrival.getSeconds() - secondsToArrival);

                  switch(i) {
                      case 0: var ziel = 'A to B'; break;
                      case 1: var ziel = 'B to C'; break;
                      case 2: var ziel = 'C to D'; break;
                      case 3: var ziel = 'D to E'; break;
                      case 4: var ziel = 'E to F'; break;
                      case 5: var ziel = 'F to G'; break;
                      case 6: var ziel = 'G to H'; break;
                      case 7: var ziel = 'H to I'; break;
                      default: var ziel = '';
                  }

                  displayText = 'segment: ' + ziel 
                                + '<br>dist: ' + route.legs[i].distance.text 
                                + '<br> time segment: ' + route.legs[i].duration.value 
                                + 's <br> seconds to arrival: ' + secondsToArrival 
                                + 's <br> time at waypoint: ' + startAtWaypoint.getHours() +':'+ startAtWaypoint.getMinutes()
                                + '<hr>' + displayText;   // notice: instead of displayText+= , I put displayText at the end, because the loop is backwards
                }
                summaryPanel.innerHTML = displayText;

                computeTotalDistance(response);
            } 
            else {
                alert("directions response " + status);
            }
        });
    }
    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("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(0) + " minutes";
    }    
</script>

example fiddle