谷歌地图JavaScript API -切换路由可见性,而不是清除它



我正在使用Google Maps JavaScript API在地图上显示驾驶路线。

我有这段代码,将从地图上完全清除路线:

directionsDisplayD.setDirections({routes: []});

是否有一种方法可以切换它的可见性?

将DirectionsRenderer对象的map属性设置为null以隐藏方向。将其设置回您的map对象以重新显示方向。

function initMap() {
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer;
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {
      lat: 41.85,
      lng: -87.65
    }
  });
  directionsDisplay.setMap(map);
  calculateAndDisplayRoute(directionsService, directionsDisplay);
  google.maps.event.addDomListener(document.getElementById("btn"), 'click', function(evt) {
    if (directionsDisplay.getMap() != null) directionsDisplay.setMap(null);
    else directionsDisplay.setMap(map);
  });
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  directionsService.route({
    origin: "New York, NY",
    destination: "Trenton, NJ",
    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%;
}
#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;
}
<input id="btn" type="button" value="toggle" />
<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>

最新更新