2017-07-24 240 views
1

我正在使用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++; 
    } 

功能requestDirections(开始,结束,WPS,驱动程序){

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

directionsRenderer.setMap(NULL); –

+0

删除旧路线时不起作用 – ankita25

+0

每次调用renderDirections()时,都会创建新的渲染器实例。将渲染器的初始化放在全局级别上,并只保留一个'google.maps.DirectionsRenderer()'实例。在这种情况下'directionsRenderer.setMap(null); '应该工作。 – xomena

回答

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 = []; 
} 
+0

没关系。根据您给出的想法,我制作了一个数组路线[],并让它们保存多条路线的经纬度点。当驱动器循环在设置的时间间隔后再次执行时,我在route []上循环删除旧数据的路径路径,但出现错误:无法读取未定义的属性'setMap'。Plz指南 – ankita25

0

这为我工作:宣布directionsRender []全球和计数器设置到旧路由环路将其清除`

function renderDirections(result, Driver) { 
     directionsRenderer[cnt] = new google.maps.DirectionsRenderer(); 
     directionsRenderer[cnt].setMap(map); 
     directionsRenderer[cnt].setDirections(result); 
     cnt++; 
    }` 
     function clearRoutes() { 
     for (var i = 0; i < cnt; i++) { 
      directionsRenderer[i].setMap(null); 
     } 
    }