2

每次我们通过方向服务搜索路线时,结果都会附加到方向面板的底部。有些人建议将 div 选项卡中的面板重置为空...任何人都可以建议如何做到这一点...

function calcRoute() {
  directionsDisplay = new google.maps.DirectionsRenderer({
    'map': map,
    'preserveViewport': false,
    'draggable': true
  });
  directionsDisplay.setPanel(
    document.getElementById("directions_panel")
  );

  // ... code to make Directions API request and display response ...
}

HTML部分:

     <div id="directions_panel" style="width:90%"></div>
4

3 回答 3

8

这应该有效:

  document.getElementById("directions_panel").innerHTML = "";
于 2013-05-16T15:24:10.447 回答
3

要清除方向面板:

directionsDisplay.setPanel(null);

使用以下命令启动方向面板:

directionsDisplay.setPanel(document.getElementById('directions_panel'));

...其中“directions_panel”是您希望加载方向的 DIV。

标记也是如此:

marker.setMap(null);

来自Google Maps Javascript API 开发人员指南

于 2016-04-21T20:48:00.973 回答
1

我认为您的代码的问题在于您DirectionsRenderer每次调用时都定义了一个新服务calcRoute

从演示中查看这段代码:

  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);
    directionsDisplay.setPanel(document.getElementById('right-panel'));

    var control = document.getElementById('floating-panel');
    control.style.display = 'block';
    map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);

    var onChangeHandler = function() {
      calculateAndDisplayRoute(directionsService, directionsDisplay);
    };
    document.getElementById('start').addEventListener('change', onChangeHandler);
    document.getElementById('end').addEventListener('change', onChangeHandler);
  }

  function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    var start = document.getElementById('start').value;
    var end = document.getElementById('end').value;
    directionsService.route({
      origin: start,
      destination: end,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

In the initMap function, the directionsDisplay and directionsService services are created. Then, they are passed to the calculateAndDisplayRoute function:

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

The calculateAndDisplayRoute then uses this existing instance of each service, rather than recreating the directionsDisplay service.

In your code, you have the following line in your calcRoute function:

directionsDisplay = new google.maps.DirectionsRenderer({
  ...
});

然后是后续调用setPanel等等。因为DirectionsRenderer每次调用时都会创建一个新实例,calcRoute所以不会更新之前的实例。您每次都需要使用相同的实例,以便重新绘制地图上的路线(而不是覆盖在前一个实例创建的路线上)并从面板中删除以前的方向(而不是拥有新的方向)简单地附加在前一个实例插入的那些之后)。

于 2017-06-22T02:34:04.930 回答