如何删除谷歌地图中的所有路线?

时间:2017-07-24 13:29:33

标签: javascript google-maps google-maps-api-3

我正在使用renderDirections和requestDirections方法创建在循环中调用的多个路由,现在我想在调用该循环之前清除它们,因为即使没有路由数据,它也会显示过去的数据。 PS:当没有数据但是它显示以前的路径时,不会调用这些方法

以下是我设置路线的示例代码:

 function renderDirections(result, Driver) {

        var directionsRenderer = new google.maps.DirectionsRenderer({ suppressMarkers: false,preserveViewport: true, polylineOptions: { strokeColor: colors[cur] } });
        directionsRenderer.setMap(map);
        directionsRenderer.setDirections(result);
        var leg = result.routes[0].legs[0];
        makeMarker(leg.start_location, Driver);
        makeMarker(leg.end_location, Driver);
        cur++;
    }

function requestDirections(start,end,wps,Driver){

        var directionsService = new google.maps.DirectionsService;
        directionsService.route(
            {
                origin: start,
                destination: end,
                waypoints: wps,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            }, function (result) {
                renderDirections(result, Driver);
            });
    }

2 个答案:

答案 0 :(得分:0)

初始化时,您可以简单地将路由放入数组中,如下所示:routes.push (myRoute)然后使用带有参数route.setMap ()的方法null消除地图中的路径。如果您重置数组,也可以删除它们:routes = [];routes[2]=null一个元素。我给你一些方法来删除或只是消失所有路线。

// Sets the map on all routes in the array.
function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
        routes[i].setMap(map);
    }
}

// Removes the routes from the map, but keeps them in the array.
function clearMarkers() {
    setMapOnAll(null);
}

// Shows any routes currently in the array.
function showMarkers() {
    setMapOnAll(map);
}

// Deletes all routes in the array by removing references to them.
function clearAllMarkers() {
    clearMarkers();
    routes = [];
}

答案 1 :(得分:0)

这对我有用:全局声明directionsRender []并设置一个计数器来循环旧路由以清除它`

varchar