Javascript 谷歌地图清除所有标记和多段线

Javascript 谷歌地图清除所有标记和多段线,javascript,google-maps,polyline,google-polyline,Javascript,Google Maps,Polyline,Google Polyline,我有一个在地图上设置路线的函数。这个函数创建从起点到终点的多段线。一旦绘制了这些线,我就可以沿着这些路径设置标记的动画 当标记沿多段线设置动画并到达其目标时,我希望从地图中清除所有覆盖 以下是我到目前为止所做的一些工作 如何做到这一点 代码 <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> <m

我有一个在地图上设置路线的函数。这个函数创建从起点到终点的多段线。一旦绘制了这些线,我就可以沿着这些路径设置标记的动画

当标记沿多段线设置动画并到达其目标时,我希望从地图中清除所有覆盖

以下是我到目前为止所做的一些工作

如何做到这一点

代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>


<style>
html{height:100%;}
body{height:100%;margin:0px;font-family: Helvetica,Arial;}
</style>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">

  var map;
  var directionDisplay;
  var directionsService;
  var stepDisplay;

  var position;
  var marker = [];
  var polyline = [];
  var poly2 = [];
  var poly = null;
  var startLocation = [];
  var endLocation = [];
  var timerHandle = [];


  var speed = 0.000005, wait = 1;
  var infowindow = null;

  var myPano;   
  var panoClient;
  var nextPanoId;

  var startLoc = new Array();
  startLoc[0] = 'rio claro, trinidad';
  startLoc[1] = 'preysal, trinidad';
  startLoc[2] = 'san fernando, trinidad';
  startLoc[3] = 'couva, trinidad';

  var endLoc = new Array();
  endLoc[0] = 'princes town, trinidad';
  endLoc[1] = 'tabaquite, trinidad';
  endLoc[2] = 'mayaro, trinidad';
  endLoc[3] = 'arima, trinidad';


  var Colors = ["#FF0000", "#00FF00", "#0000FF"];


function initialize() {  

  infowindow = new google.maps.InfoWindow(
    { 
      size: new google.maps.Size(150,50)
    });

    var myOptions = {
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    address = 'Trinidad and Tobago'
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
     map.fitBounds(results[0].geometry.viewport);

    }); 
  // setRoutes();
  } 


function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
    var contentString = '<b>'+label+'</b><br>'+html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: label,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        marker.myname = label;


    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
    return marker;
}  

function setRoutes(){   

    var directionsDisplay = new Array();

    for (var i=0; i< startLoc.length; i++){

    var rendererOptions = {
        map: map,
        suppressMarkers : true,
        preserveViewport: true
    }
    directionsService = new google.maps.DirectionsService();

    var travelMode = google.maps.DirectionsTravelMode.DRIVING;  

    var request = {
        origin: startLoc[i],
        destination: endLoc[i],
        travelMode: travelMode
    };  

        directionsService.route(request,makeRouteCallback(i,directionsDisplay[i]));

    }   


    function makeRouteCallback(routeNum,disp){
        if (polyline[routeNum] && (polyline[routeNum].getMap() != null)) {
         startAnimation(routeNum);
         return;
        }
        return function(response, status){

          if (status == google.maps.DirectionsStatus.OK){

            var bounds = new google.maps.LatLngBounds();
            var route = response.routes[0];
            startLocation[routeNum] = new Object();
            endLocation[routeNum] = new Object();


            polyline[routeNum] = new google.maps.Polyline({
            path: [],
            strokeColor: '#FFFF00',
            strokeWeight: 3
            });

            poly2[routeNum] = new google.maps.Polyline({
            path: [],
            strokeColor: '#FFFF00',
            strokeWeight: 3
            });     


            // For each route, display summary information.
            var path = response.routes[0].overview_path;
            var legs = response.routes[0].legs;


            disp = new google.maps.DirectionsRenderer(rendererOptions);     
            disp.setMap(map);
            disp.setDirections(response);


            //Markers               
            for (i=0;i<legs.length;i++) {
              if (i == 0) { 
                startLocation[routeNum].latlng = legs[i].start_location;
                startLocation[routeNum].address = legs[i].start_address;
                // marker = google.maps.Marker({map:map,position: startLocation.latlng});
                marker[routeNum] = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
              }
              endLocation[routeNum].latlng = legs[i].end_location;
              endLocation[routeNum].address = legs[i].end_address;
              var steps = legs[i].steps;

              for (j=0;j<steps.length;j++) {
                var nextSegment = steps[j].path;                
                var nextSegment = steps[j].path;

                for (k=0;k<nextSegment.length;k++) {
                    polyline[routeNum].getPath().push(nextSegment[k]);
                    //bounds.extend(nextSegment[k]);
                }

              }
            }

         }       

         polyline[routeNum].setMap(map);
         //map.fitBounds(bounds);
         startAnimation(routeNum);  

    } // else alert("Directions request failed: "+status);

  }

}

    var lastVertex = 1;
    var stepnum=0;
    var step = 50; // 5; // metres
    var tick = 100; // milliseconds
    var eol= [];
//----------------------------------------------------------------------                
 function updatePoly(i,d) {
 // Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
    if (poly2[i].getPath().getLength() > 20) {
          poly2[i]=new google.maps.Polyline([polyline[i].getPath().getAt(lastVertex-1)]);
          // map.addOverlay(poly2)
        }

    if (polyline[i].GetIndexAtDistance(d) < lastVertex+2) {
        if (poly2[i].getPath().getLength()>1) {
            poly2[i].getPath().removeAt(poly2[i].getPath().getLength()-1)
        }
            poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),polyline[i].GetPointAtDistance(d));
    } else {
        poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),endLocation[i].latlng);
    }
 }
//----------------------------------------------------------------------------

function animate(index,d) {
   if (d>eol[index]) {

      marker[index].setPosition(endLocation[index].latlng);
      return;
   }
    var p = polyline[index].GetPointAtDistance(d);

    //map.panTo(p);
    marker[index].setPosition(p);
    updatePoly(index,d);
    timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);
}

//-------------------------------------------------------------------------

function startAnimation(index) {
        if (timerHandle[index]) clearTimeout(timerHandle[index]);
        eol[index]=polyline[index].Distance();
        map.setCenter(polyline[index].getPath().getAt(0));

        poly2[index] = new google.maps.Polyline({path: [polyline[index].getPath().getAt(0)], strokeColor:"#FFFF00", strokeWeight:3});

        timerHandle[index] = setTimeout("animate("+index+",50)",2000);  // Allow time for the initial map display
}

//----------------------------------------------------------------------------    



</script>
</head>
<body onload="initialize()">

<div id="tools">

    <button onclick="setRoutes();">Start</button>

</div>

<div id="map_canvas" style="width:100%;height:100%;"></div>

</body>
</html>

谷歌地图JavaScript API v3示例:方向复杂
html{高度:100%;}
正文{高度:100%;边距:0px;字体系列:Helvetica,Arial;}
var映射;
方向显示;
var定向服务;
var步进显示;
var位置;
var标记=[];
var多段线=[];
var poly2=[];
var-poly=null;
var=[];
var endLocation=[];
var timerHandle=[];
var速度=0.000005,等待=1;
var infowindow=null;
myPano变种;
客户机;
nextPanoId变种;
var startoc=新数组();
Startoc[0]=“特立尼达的里约克拉罗”;
Startoc[1]=“特立尼达岛preysal”;
Startoc[2]=“特立尼达岛圣费尔南多”;
Startoc[3]=“库瓦,特立尼达”;
var endLoc=新数组();
endLoc[0]=“特立尼达王子镇”;
endLoc[1]=“特立尼达岛塔巴基特”;
endLoc[2]=“特立尼达的马亚罗”;
endLoc[3]=“特立尼达岛阿里玛”;
变量颜色=[“FF0000”、“00FF00”、“0000FF”];
函数初始化(){
infowindow=新建google.maps.infowindow(
{ 
尺寸:新谷歌地图尺寸(150,50)
});
变量myOptions={
缩放:10,
mapTypeId:google.maps.mapTypeId.ROADMAP
}
map=new google.maps.map(document.getElementById(“map_canvas”),myOptions);
地址='特立尼达和多巴哥'
geocoder=新的google.maps.geocoder();
geocoder.geocode({'address':address},函数(结果,状态){
map.fitBounds(结果[0].geometry.viewport);
}); 
//setRoutes();
} 
函数createMarker(板条、标签、html){
//警报(“createMarker”(“+latlng+”、“+label+”、“+html+”、“+color+”));
var contentString=''+label+'
'+html; var marker=new google.maps.marker({ 位置:latlng, 地图:地图, 标题:标签,
zIndex:Math.round(latlng.lat()*-100000)您应该能够通过以下操作完成此任务:

首先,在
setRoutes()
中,调用方向渲染器抑制多段线(您已经在绘制自己的多段线):

然后在
animate()
中,将所有标记和多段线设置为在管线结束时隐藏:

   if (d>eol[index]) {
        marker[index].setVisible(false);
        polyline[index].setVisible(false);
         poly2[index].setVisible(false);
         marker[index].setPosition(endLocation[index].latlng);
         return;
      }

在这里找到您修改过的示例:

错误很明显
makeRouteCallback没有定义
。您确定它在使用它的范围内吗?鉴于您在文章中分解代码的方式,很难说。您是否有一个JSFIDLE显示问题?好的,我看到问题makeRouteCallback是一个回调函数在SetRoutes()中。我将修改我的代码,但我有兴趣在标记到达多段线末端后扩展多段线。你能就此向我提供建议吗?谢谢you@geocodezip我更新了问题,并包含了一个类似代码的jsbin演示。我还包含了一个关于我想在测试代码中实现什么的描述。@geocodezip我尝试了一些关于n我的代码但是我没有改变多段线的目标。@geocodezip你能帮我吗?我只是没有让它工作。你能告诉我如果我必须等到所有标记完成动画,我会怎么做吗?如果我有'if(completed==startoc.length){}'一旦为true,则表示所有标记移动的完成。我正在尝试此操作。我创建了一个循环并迭代设置标记和多段线。setVisible(false)并在循环外部放置了return语句。但是,只有标记被清除,多段线保留。
   if (d>eol[index]) {
        marker[index].setVisible(false);
        polyline[index].setVisible(false);
         poly2[index].setVisible(false);
         marker[index].setPosition(endLocation[index].latlng);
         return;
      }