强制停止以映射动画

时间:2016-12-23 12:00:14

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

当用户点击地图并在释放鼠标按钮之前将其拖动时,地图会继续移动一段时间。 有没有办法强制停止滑动?

运行下面的代码段,并在地图静止时单击按钮。效果很好。

现在将地图设置为动态,然后在地图停止前单击其中一个按钮。当显示新路线时,地图动画会继续。

我不想完全禁用拖动选项,如此

map.setOptions({ draggable: false });

我想强制停止地图的任何动作,因此它不会传播到正在显示的下一条路线。



function initMap() {
  var directionsDisplay = new google.maps.DirectionsRenderer;
  var directionsService = new google.maps.DirectionsService;
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 7,
    center: {lat: 41.85, lng: -87.65}
  });

  directionsDisplay.setMap(map);

  var buttonClick = function() {
    calculateAndDisplayRoute(directionsService, directionsDisplay, this);
  };

  var btnRoute1 = document.getElementById("btnRoute1");
  btnRoute1.addEventListener("click", buttonClick);

  var btnRoute2 = document.getElementById("btnRoute2");
  btnRoute2.addEventListener("click", buttonClick);

  map.controls[google.maps.ControlPosition.TOP_CENTER].push(btnRoute1);
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(btnRoute2);
}

function calculateAndDisplayRoute(directionsService, directionsDisplay, clickedButton) {
  var origin = clickedButton.getAttribute("data-origin");
  var destination = clickedButton.getAttribute("data-destination");
  directionsService.route({
    origin: origin,
    destination: destination,
    travelMode: "DRIVING"
  }, function(response, status) {
    if (status === "OK") {
      directionsDisplay.setDirections(response);
	} else {
      window.alert("Directions request failed due to " + status);
	}
  });
}

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 100%;
}

button {
  margin: 10px;
}

<html>
 <body>
   <button id="btnRoute1" data-origin="chicago, il" data-destination="st louis, mo">Chicago -> St Louis</button>
    <button id="btnRoute2" data-origin="chicago, il" data-destination="los angeles, ca">Chicago -> Los Angeles</button>
    <div id="map"></div>
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
  </body>
</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案