【问题标题】:Removing routes rendered on a Google Map删除在 Google 地图上呈现的路线
【发布时间】:2011-12-14 17:26:09
【问题描述】:

我正在尝试做一些我之前已经做过很多次的事情,尽管我在完成它时遇到了一些困难。

我有一个显示三个 Google 地图的网页。

对于这些谷歌地图中的每一个,我都有一个接受邮政编码/邮政编码的文本框和一个“获取路线”按钮。

点击这些按钮中的每一个都会使用 google.maps.DirectionsService 对象在页面底部居中的一个面板中显示一组方向。

当我尝试通过再次搜索找到新路线时,我的问题出现了。如下图所示,两条路线都被渲染了。


我在最后有一个标记,它位于标记集合中。

我已经读过几次关于如何循环遍历这个数组并使用 marker.setMap(null) 来清除这个标记的内容。

但是,我似乎无法在每次特定搜索后清除实际路线。

有人在清除多张地图上的标记时遇到过问题吗?

你必须以某种方式完全重置地图吗?

如果您必须清除标记,您应该在流程生命周期的哪个阶段执行此操作,以便您的新旅程出现在搜索之后,但旧的旅程被删除?

【问题讨论】:

    标签: javascript google-maps routes google-maps-markers


    【解决方案1】:

    我对所有三个 Google 地图都使用相同的 google.maps.DirectionsService 对象,它们都调用相同的方法来计算方向,但将它们自己的地图对象作为参数传入。

    function calcRoute(startPoint, location_arr) {
        // Create a renderer for directions and bind it to the map.
        var map = location_arr[LOCATION_ARR_MAP_OBJECT];
        var rendererOptions = {
        map: map
    }
    
    if(directionsDisplay != null) {
        directionsDisplay.setMap(null);
        directionsDisplay = null;
    }
    
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    
    directionsDisplay.setMap(map);
    
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    

    要点是如果方向显示!= null,我们不仅将 null 传递给 setMap,我们还使整个对象无效,我发现这解决了它。

    【讨论】:

    • 遇到了同样的问题,点击 setMap(null); 之后的另一个引脚;显示了一小会旧路线,然后显示新路线,(旧路线有点闪烁)。但是将旧的 DirectionsRenderer 设置为 null 并按照建议创建新的可以解决问题。
    【解决方案2】:

    我不知道答案……很可能你需要做的只是视情况而定:

    // put the codes after direction service is declared or run directionsService //
    
    directionsDisplay.setMap(null); // clear direction from the map
    directionsDisplay.setPanel(null); // clear directionpanel from the map          
    directionsDisplay = new google.maps.DirectionsRenderer(); // this is to render again, otherwise your route wont show for the second time searching
    directionsDisplay.setMap(map); //this is to set up again
    

    【讨论】:

      【解决方案3】:

      这是您唯一需要的部分:

      // Clear past routes
          if (directionsDisplay != null) {
              directionsDisplay.setMap(null);
              directionsDisplay = null;
          }
      

      【讨论】:

        【解决方案4】:

        这对我有用

        // on initiate map
        // this listener is not necessary unless you use listener
        google.maps.event.addListener(directionsRenderer, 'directions_changed', function () {
            if(directionsRenderer.directions === null){
                return;
            }
            // other codes
        });
        
        // on clear method
        directionsRenderer.set('directions', null);
        

        【讨论】:

          猜你喜欢
          • 2011-07-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-28
          • 1970-01-01
          • 2011-07-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多