google 具有多个颜色方向的地图方向

google map direction with multiple directions with colors

我需要在地图方向上填充以下数据

dataset 1
    [
        [lat, lon],
        [lat, lon],
        [lat, lon],
    ],
dataset 2
    [
        [lat, lon],
        [lat, lon],
        [lat, lon],
    ],   
So On ... 

所有数据集都应该有带有唯一颜色的路线,任何数据集都可以超过 8 waypoints 限制。我可以通过 https://lemonharpy.wordpress.com/2011/12/15/working-around-8-waypoint-limit-in-google-maps-directions-api/ and Plotting more than 8 waypoints in Google Maps v3.

等在线教程修复 8 个路点限制

但我发现无法为每个数据集获取不同颜色的路线。

这是我的代码

<style>
#map {
       height: 1080px;
       width: 100%;
       border: 1px solid #000;  
     }

</style>

<div id="map"></div>
<script>
function initMap() {
    //console.log("sdsfsd");
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 14,
      center: {lat: 28.6247, lng: 77.3731},
      disableDefaultUI:true,
      //28.6247375!4d77.3731819
    });

    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer({suppressInfoWindows: true, suppressMarkers: true 
    });


    var response = {"abcd": {"points":
    [
        [28.5435,77.2051,"2016-07-17 08:02:18 - 28.543500 - 77.205100"],
        [28.5313,77.249,"2016-07-17 12:32:38 - 28.531300 - 77.249000"],
        [28.5279,77.2462,"2016-07-17 12:35:02 - 28.527900 - 77.246200"],
        [28.5328,77.2391,"2016-07-17 12:36:42 - 28.532800 - 77.239100"],
        [28.5407,77.24,"2016-07-17 12:38:23 - 28.540700 - 77.240000"],
        [28.543,77.2139,"2016-07-17 12:42:36 - 28.543000 - 77.213900"],
        [28.5429,77.2095,"2016-07-17 12:43:26 - 28.542900 - 77.209500"],
        [28.5332,77.2071,"2016-07-17 12:48:30 - 28.533200 - 77.207100"],
        [28.531,77.2113,"2016-07-17 12:52:43 - 28.531000 - 77.211300"],
        [28.5315,77.2077,"2016-07-17 13:03:15 - 28.531500 - 77.207700"],
        [28.5433,77.2117,"2016-07-17 13:08:27 - 28.543300 - 77.211700"],
        [28.5412,77.2374,"2016-07-17 13:12:50 - 28.541200 - 77.237400"],
        [28.5311,77.2482,"2016-07-17 17:49:02 - 28.531100 - 77.248200"]
    ]},
    "ret-abcd": {"points":[
    [28.5294,77.2502,"2016-07-18 07:29:38 - 28.529400 - 77.250200"],
    [28.5541,77.2637,"2016-07-18 07:43:59 - 28.554100 - 77.263700"],
    [28.5635,77.2648,"2016-07-18 07:46:08 - 28.563500 - 77.264800"],
    [28.5721,77.2579,"2016-07-18 07:48:07 - 28.572100 - 77.257900"],
    [28.5746,77.2608,"2016-07-18 07:49:14 - 28.574600 - 77.260800"],
    [28.5787,77.2813,"2016-07-18 07:51:16 - 28.578700 - 77.281300"],
    [28.5731,77.3086,"2016-07-18 07:52:39 - 28.573100 - 77.308600"],
    [28.5902,77.336,"2016-07-18 07:58:00 - 28.590200 - 77.336000"],
    [28.6252,77.3735,"2016-07-18 08:49:47 - 28.625200 - 77.373500"]
    ]
    }
    };

var timeout = 100;
var m = 0;
var cnt = 0;
var markers = [];
var combinedResults;
var directionsResultsReturned = 0;
var linecolors = ['red', 'blue', 'green', 'yellow'];

for(key in response) {
    if(response[key].points.length > 0) {
            var blocks = [];
            var k = 0;
            for(var i=0;i<response[key].points.length;i++) {
                if(i != 0 && i % 10 == 0) {
                    k++;
                }
                //console.log(k);
                if(typeof blocks[k] == 'undefined') {
                    blocks[k] = [];
                }

                blocks[k].push(response[key].points[i]);
            }
            //var ds = [];
            //var dd = [];
            ds = new google.maps.DirectionsService;
            dd = new google.maps.DirectionsRenderer({suppressInfoWindows: true, suppressMarkers: true});
            dd.setMap(map);

            for(i=0;i<blocks.length;i++) {

                /*ds[m] = new google.maps.DirectionsService;
                dd[m] = new google.maps.DirectionsRenderer({suppressInfoWindows: true, suppressMarkers: true, polylineOptions: {
                  strokeColor: linecolors[i]
                }});
                dd[m].setMap(map);
                */

                waypts = [];
                markers.push([blocks[i][0][0], blocks[i][0][1], blocks[i][0][2]]);
                for(var j=1;j<blocks[i].length-1;j++) {
                    waypts.push({
                        location: blocks[i][j][0]+','+blocks[i][j][1],
                        stopover: true
                    });
                    //var myLatlng = new google.maps.LatLng(blocks[i][j][0],blocks[i][j][1]);
                    markers.push([blocks[i][j][0],blocks[i][j][1],blocks[i][j][2]]);

                }
                markers.push([blocks[i][blocks[i].length-1][0], blocks[i][blocks[i].length-1][1], blocks[i][blocks[i].length-1][2]]);
                //data.start[0]+','+data.start[1],
                //ds[m].route({   

                dd.setOptions({suppressInfoWindows: true, suppressMarkers: true, polylineOptions: {
                  strokeColor: linecolors[cnt%3]
                }});
                ds.route({
                        'origin': blocks[i][0][0]+','+blocks[i][0][1],
                        'destination': blocks[i][blocks[i].length-1][0]+','+blocks[i][blocks[i].length-1][1],
                        'waypoints': waypts,
                        'travelMode': 'DRIVING'
                    },
                    function (directions, status){
                        //console.log(dd[m]);
                        if (status == google.maps.DirectionsStatus.OK) {

                            if (directionsResultsReturned == 0) { // first bunch of results in. new up the combinedResults object
                                combinedResults = directions;
                                directionsResultsReturned++;
                            }
                            else {
                                // only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
                                // directionResults object, but enough to draw a path on the map, which is all I need
                                combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(directions.routes[0].legs);
                                combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(directions.routes[0].overview_path);

                                combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(directions.routes[0].bounds.getNorthEast());
                                combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(directions.routes[0].bounds.getSouthWest());
                                directionsResultsReturned++;
                            }
                            //dd[m].setOptions({suppressInfoWindows: true, suppressMarkers: true, polylineOptions: {


                            if (directionsResultsReturned == blocks.length) { // we've received all the results. put to map 
                                //dd[m].setDirections(combinedResults);
                                dd.setDirections(combinedResults);
                            }    
                            /*dd[m].setDirections(directions);
                            console.log(i);
                            console.log(linecolors[i%3])
                            dd[m].setOptions({suppressInfoWindows: true, suppressMarkers: true, polylineOptions: {
                              strokeColor: linecolors[i%3]
                          }});*/
                        }
                    }
                );

            }    
    }

    for(h=0;h<markers.length;h++) {
        createMapMarker(map, new google.maps.LatLng(markers[h][0],markers[h][1]), markers[h][2], "", "");
    }
    cnt++;

}
}
function createMapMarker(map, latlng, label, html, sign) {
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: "http://www.google.com/mapfiles/marker"+ sign +".png",
        title: label,
        //zIndex: Math.round(latlng.lat()*-100000)<<5
    });

    marker.myname = label;


    return marker;
} 

</script>

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>

key是数据集id

更新:更新了 运行 代码,只有 google api 键需要更换

您需要为每个数据集创建一个 DirectionsRenderer。如果数据集包含超过 8 个 waypoints,您将需要合并来自 DirectionsService 的结果。

proof of concept fiddle

代码片段:

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 14,
    center: {
      lat: 28.6247,
      lng: 77.3731
    },
    disableDefaultUI: true,
  });

  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
    suppressInfoWindows: true,
    suppressMarkers: true
  });

  var response = {
    "abcd": {
      "points": [
        [28.5435, 77.2051, "2016-07-17 08:02:18 - 28.543500 - 77.205100"],
        [28.5313, 77.249, "2016-07-17 12:32:38 - 28.531300 - 77.249000"],
        [28.5279, 77.2462, "2016-07-17 12:35:02 - 28.527900 - 77.246200"],
        [28.5328, 77.2391, "2016-07-17 12:36:42 - 28.532800 - 77.239100"],
        [28.5407, 77.24, "2016-07-17 12:38:23 - 28.540700 - 77.240000"],
        [28.543, 77.2139, "2016-07-17 12:42:36 - 28.543000 - 77.213900"],
        [28.5429, 77.2095, "2016-07-17 12:43:26 - 28.542900 - 77.209500"],
        [28.5332, 77.2071, "2016-07-17 12:48:30 - 28.533200 - 77.207100"],
        [28.531, 77.2113, "2016-07-17 12:52:43 - 28.531000 - 77.211300"],
        [28.5315, 77.2077, "2016-07-17 13:03:15 - 28.531500 - 77.207700"],
        [28.5433, 77.2117, "2016-07-17 13:08:27 - 28.543300 - 77.211700"],
        [28.5412, 77.2374, "2016-07-17 13:12:50 - 28.541200 - 77.237400"],
        [28.5311, 77.2482, "2016-07-17 17:49:02 - 28.531100 - 77.248200"]
      ]
    },
    "ret-abcd": {
      "points": [
        [28.5294, 77.2502, "2016-07-18 07:29:38 - 28.529400 - 77.250200"],
        [28.5541, 77.2637, "2016-07-18 07:43:59 - 28.554100 - 77.263700"],
        [28.5635, 77.2648, "2016-07-18 07:46:08 - 28.563500 - 77.264800"],
        [28.5721, 77.2579, "2016-07-18 07:48:07 - 28.572100 - 77.257900"],
        [28.5746, 77.2608, "2016-07-18 07:49:14 - 28.574600 - 77.260800"],
        [28.5787, 77.2813, "2016-07-18 07:51:16 - 28.578700 - 77.281300"],
        [28.5731, 77.3086, "2016-07-18 07:52:39 - 28.573100 - 77.308600"],
        [28.5902, 77.336, "2016-07-18 07:58:00 - 28.590200 - 77.336000"],
        [28.6252, 77.3735, "2016-07-18 08:49:47 - 28.625200 - 77.373500"]
      ]
    }
  };

  var timeout = 100;
  var m = 0;
  var cnt = 0;
  var markers = [];
  var combinedResults;
  var directionsResultsReturned = 0;
  var linecolors = ['red', 'blue', 'green', 'yellow'];
  var colorIdx = 0;
  var dd = [];

  for (key in response) {
    if (response[key].points.length > 0) {
      var blocks = [];
      var k = 0;
      for (var i = 0; i < response[key].points.length; i++) {
        if (i != 0 && i % 10 == 0) {
          k++;
        }
        //console.log(k);
        if (typeof blocks[k] == 'undefined') {
          blocks[k] = [];
        }

        blocks[k].push(response[key].points[i]);
      }

      ds = new google.maps.DirectionsService;

      for (i = 0; i < blocks.length; i++) {

        waypts = [];
        markers.push([blocks[i][0][0], blocks[i][0][1], blocks[i][0][2]]);
        for (var j = 1; j < blocks[i].length - 1; j++) {
          waypts.push({
            location: blocks[i][j][0] + ',' + blocks[i][j][1],
            stopover: true
          });
          //var myLatlng = new google.maps.LatLng(blocks[i][j][0],blocks[i][j][1]);
          markers.push([blocks[i][j][0], blocks[i][j][1], blocks[i][j][2]]);

        }
        markers.push([blocks[i][blocks[i].length - 1][0], blocks[i][blocks[i].length - 1][1], blocks[i][blocks[i].length - 1][2]]);
        //data.start[0]+','+data.start[1],
        //ds[m].route({   

        ds.route({
            'origin': blocks[i][0][0] + ',' + blocks[i][0][1],
            'destination': blocks[i][blocks[i].length - 1][0] + ',' + blocks[i][blocks[i].length - 1][1],
            'waypoints': waypts,
            'travelMode': 'DRIVING'
          },
          function(directions, status) {
            dd.push(new google.maps.DirectionsRenderer({
              suppressInfoWindows: true,
              suppressMarkers: true,
              polylineOptions: {
                strokeColor: linecolors[colorIdx++ % 3]
              },
              map: map
            }));

            if (status == google.maps.DirectionsStatus.OK) {
              dd[dd.length - 1].setDirections(directions);
            }
          }
        );

      }
    }

    for (h = 0; h < markers.length; h++) {
      createMapMarker(map, new google.maps.LatLng(markers[h][0], markers[h][1]), markers[h][2], "", "");
    }
    cnt++;

  }
}

function createMapMarker(map, latlng, label, html, sign) {
  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    icon: "http://www.google.com/mapfiles/marker" + sign + ".png",
    title: label,
  });

  marker.myname = label;


  return marker;
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
#map {
  height: 100%;
  width: 100%;
  border: 1px solid #000;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

根据您的数据集,您可以通过设置开始、结束和 waypoints 来实现这一点 value.this 可以通过 java 脚本完全实现。

稍后,如果您愿意,可以在 div 中显示路线摘要信息。 这是在此代码块中显示摘要的div。

    var start = cities[0];
    var end = cities[cities.length - 1];
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 6,
              center: initialLocation
           });
   directionsDisplay.setMap(map);

   calculateAndDisplayRoute(directionsService, directionsDisplay);

function calculateAndDisplayRoute(directionsService,
   directionsDisplay) {

       cities.shift();//remove start city
       cities.pop();//remove end city

       var wayPts = [];
       for (var i = 0; i < cities.length; i++) {
          wayPts.push({
               location: cities[i],
               stopover: true
              });
         }
         directionsService.route({
              origin: start,
              destination: end,
              waypoints: wayPts,
              optimizeWaypoints: true,
              travelMode: 'DRIVING'
          }, function (response, status) {
                if (status === 'OK') {
                    directionsDisplay.setDirections(response);
                    var route = response.routes[0];
                    var summaryPanel = document.getElementById('directions-panel');
                    summaryPanel.innerHTML = '';
                    // For each route, display summary information.
                    for (var i = 0; i < route.legs.length; i++) {
                        var routeSegment = i + 1;
                        summaryPanel.innerHTML += '<b><font color="#8a2be2"> Route Segment: ' + routeSegment +
                            '</b></font><br>';
                        summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
                        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
                        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
                    }
                } else {
                    window.alert('Directions request failed due to ' + status);
                }
            });
        }