在同一Google地图上同时显示多个路线

时间:2017-07-27 08:46:01

标签: javascript html html5 google-maps google-maps-api-3

我希望Google地图能够同时显示多个来自同一目的地的多条路线。目的地是一个明确定义的地址,但起源是逗号分隔的字符串。当我运行一个循环来绘制谷歌地图上的所有路线,在每次迭代中为一个目的地对创建一个目的地对,它会覆盖先前的路线并创建新路线。我希望保留旧路线(以前的原点,目的地对)以及在同一地图上同时显示的新路线(新原点,目的地对)。 如何在不覆盖旧路线的情况下这样做。请帮忙。

代码

<div id="foo" data-info="hi there"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
//directions.js
MarketInfo = [
  ["GARIAHAT KMC MARKET", "K.M.C. Market, 3rd Floor Market Complex, 212, Rash Behari Avenue Road, Hindustan Park, Gariahat, Kolkata- 700019", "MAJOR (1400SHOP + HOWKER)", "FRUITS ETC", "", "", "BARABAZAR, KOLEYMART", "HOWRAH, BAGHAJATIN", "We colllect...", "", "MANY", "Cars, Light goods...", "Within one hour", "", "", "No problems", "", "IF A UNLOADING..."]
];

1 个答案:

答案 0 :(得分:1)

您只有一个DirectionsRenderer。您需要为要显示的每个路线初始化一个新的DirectionsRenderer。因此,在calculateAndDisplayRoute函数中创建一个新的DirectionsRenderer。

//directions.js
MarketInfo = [
  ["GARIAHAT KMC MARKET", "K.M.C. Market, 3rd Floor Market Complex, 212, Rash Behari Avenue Road, Hindustan Park, Gariahat, Kolkata- 700019", "MAJOR (1400SHOP + HOWKER)", "FRUITS ETC", "", "", "BARABAZAR, KOLEYMART", "HOWRAH, BAGHAJATIN", "We colllect...", "", "MANY", "Cars, Light goods...", "Within one hour", "", "", "No problems", "", "IF A UNLOADING..."]
];
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Directions service (complex)</title>
  <style>
    #map {
      height: 100%;
    }
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #floating-panel {
      position: absolute;
      top: 10px;
      left: 25%;
      z-index: 5;
      background-color: #fff;
      padding: 5px;
      border: 1px solid #999;
      text-align: center;
      font-family: 'Roboto', 'sans-serif';
      line-height: 30px;
      padding-left: 10px;
    }
    
    #warnings-panel {
      width: 100%;
      height: 10%;
      text-align: center;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  &nbsp;
  <div id="warnings-panel"></div>
  <script src="directions.js"></script>
  <script>
    function initialize() {
      var markerArray = [];
      var directionsService = new google.maps.DirectionsService;
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 5,
        center: {
          lat: 22.771,
          lng: 88.974
        }
      });

      var directionsDisplay = new google.maps.DirectionsRenderer({
        map: map
      });
      calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, map);

      var onChangeHandler = function() {
        calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, map);
      };

      //document.getElementById('start').addEventListener('change', onChangeHandler);
      //document.getElementById('end').addEventListener('change', onChangeHandler);
    }


    function calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, map) {

      for (var i = 0; i < markerArray.length; i++) {
        markerArray[i].setMap(null);
      }

      for (pos in MarketInfo) {
        var row = MarketInfo[pos];
        // Second loop for multiple destination
        var str_array = row[7].split(',');
        for (var j = 0; j < str_array.length; j++) {
          directionsService.route({
            origin: str_array[j],
            destination: row[1],
            travelMode: 'DRIVING'
          }, function(response, status) {
            if (status === 'OK') {
              document.getElementById('warnings-panel').innerHTML = '<b>' + response.routes[0].warnings + '</b>';
              var dirDisplay = new google.maps.DirectionsRenderer({
                 map: map
              });
              dirDisplay.setDirections(response);
            } else {
              window.alert('Directions request failed due to ' + status);
            }
          });
        }
      }
    }
  </script>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBbXta5ppMyzPmTCGNsyP-djMlSOGJ9t9o&callback=initialize">
  </script>
</body>

</html>