删除在Google地图上呈现的路线

时间:2011-10-25 07:40:46

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

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

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

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

点击其中每个按钮,使用google.maps.DirectionsService对象在以页面底部为中心的一个面板中显示一组路线。

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

Two routes rendered on a map

我最后在标记集合中有一个标记。

我现在已经阅读了几次关于如何循环遍历此数组并使用marker.setMap(null)清除此标记的内容。

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

有没有人在清除多张地图上的标记时遇到任何问题?

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

如果您必须清除标记,那么您应该在流程的生命周期中的哪个位置执行此操作,以便在搜索后显示新的旅程,但旧的旅程会被删除?

4 个答案:

答案 0 :(得分:17)

我为所有三个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"));

要点是如果directionsDisplay!= null,我们不仅会将null传递给setMap,我们也会在之后使整个对象无效,我发现它已修复它。

答案 1 :(得分:2)

这是您需要的唯一部分:

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

答案 2 :(得分:1)

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

// 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 :(得分:0)

这对我有用

// 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);
相关问题