谷歌地图有两条路线叠加在一起

时间:2016-08-09 20:22:34

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

我有一张地图,我希望使用Google Maps Route API设置计划路线和行走路线。

我正在做的是获取计划路线的腿并将其添加到地图中。路线颜色为灰色。然后我添加通常在计划路线之上的旅行路线。该路线颜色为蓝色。我将计划路线的不透明度设置为1,将行驶路线设置为.75。

有时,当页面加载时,计划的路线位于顶部,有时是行进的路线。我想这是从谷歌获取数据,由于Javascript的性质,它不会按顺序返回。

我正在寻找的是在旅行之前总是计划路线负荷。我的计划是听取一个事件并使用一个承诺。

我应该听哪些事件?

1 个答案:

答案 0 :(得分:0)

DirectionsRenderer上唯一可用的事件是directions_changed:

  

<强>事件

     

directions_changed |参数:无

     

当渲染的路线发生变化时,无论是设置了新的DirectionsResult,还是当用户完成将更改拖动到路线路径时,都会触发此事件。

proof of concept fiddle

代码段

&#13;
&#13;
var map;
var directionsService;
var directionsDisplays = [];

function initMap() {
  directionsService = new google.maps.DirectionsService;
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 41.85,
      lng: -87.65
    }
  });
  var directionsDisplay = new google.maps.DirectionsRenderer();
  directionsDisplays.push(directionsDisplay);
  calculateAndDisplayRoute("New York, NY", "Los Angeles, CA", {
    strokeWeight: 8,
    strokeOpacity: 1.0,
    strokeColor: "white"
  }, true);
  // directionsDisplay.setMap(map);
  google.maps.event.addListener(directionsDisplays[0], 'directions_changed', function() {
    var directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplays.push(directionsDisplay);
    calculateAndDisplayRoute("New York, NY", "Denville,NJ", {
      strokeWeight: 4,
      strokeOpacity: 0.5,
      strokeColor: "blue"
    }, false);
  });

}

function calculateAndDisplayRoute(start, end, options, preserveViewport) {
  directionsService.route({
    origin: start,
    destination: end,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      directionsDisplays[directionsDisplays.length - 1].setOptions({
        map: map,
        polylineOptions: options,
        preserveViewport: preserveViewport
      });
      directionsDisplays[directionsDisplays.length - 1].setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}
&#13;
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
#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;
}
&#13;
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
&#13;
&#13;
&#13;