Javascript 删除在Google地图上渲染的路线

Javascript 删除在Google地图上渲染的路线,javascript,google-maps,routes,google-maps-markers,Javascript,Google Maps,Routes,Google Maps Markers,我正在尝试做一些我认为以前已经做过很多次的事情,尽管我在完成它时遇到了一些困难 我有一个网页,显示三个谷歌地图 对于每一个谷歌地图,我都有一个文本框,可以接受邮政编码/邮政编码,还有一个“获取方向”按钮 单击这些按钮中的每一个都会使用google.maps.DirectionsService对象在页面底部居中的一个面板中显示一组方向 当我试图通过再次搜索来找到新路线时,我的问题就出现了。如下图所示,两条路线都进行了渲染 我在最后有一个马克笔,它在马克笔收藏中 我已经读过几次关于如何循环这个数

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

我有一个网页,显示三个谷歌地图

对于每一个谷歌地图,我都有一个文本框,可以接受邮政编码/邮政编码,还有一个“获取方向”按钮

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

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


我在最后有一个马克笔,它在马克笔收藏中

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

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

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

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


如果您必须清除标记,您应该在流程生命周期的什么时候这样做,以便在搜索后显示新旅程,但删除旧旅程?

我对所有三个google maps使用相同的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,我们还将整个对象在磨损后置为null,我发现它已修复。

我不知道答案。。。。最有可能的是,你需要做的就是根据具体情况:

// 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

这是您唯一需要的部分:

// Clear past routes
    if (directionsDisplay != null) {
        directionsDisplay.setMap(null);
        directionsDisplay = null;
    }
这对我有用

// 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);

面对同样的问题,点击setMap(null)后的另一个pin;显示了一会儿旧路线,然后显示了新路线(旧路线有点闪烁)。但将旧的DirectionsRenderer设置为null并创建新的DirectionsRenderer解决了建议的问题。