我正在使用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++;
}
函数请求方向(开始, 结束, 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);
});
}
初始化路由时,您可以简单地将路由放入数组中,如下所示:routes.push (myRoute)
和接下来使用带有参数null
的方法route.setMap ()
将它们从地图中消失。如果像这样重置数组,也可以删除它们:一个元素的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 = [];
}
这对我有用:全局声明方向渲染[]并设置一个计数器以在旧路线上循环以清除它">
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);
}
}