2012-01-30 91 views
0

我有一个MVCArray存储我的多段线路径,但当用户更改其选择时,我需要清除MVCArray。相关代码如下。使用Google Maps API V3无法删除MVCArray /多段线

routePoints = new google.maps.MVCArray(); 
xmlhttp.onreadystatechange=function() { 
      if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
       markersArray = eval("(" + xmlhttp.responseText + ")"); 
       removeLines(); 
       for (var i = 0; i < markersArray.length; i++) { 
        var address = new google.maps.LatLng(markersArray[i][0], markersArray[i][1]); 
        routePoints.insertAt(routePoints.length, address); 
       } 
       routePath = new google.maps.Polyline({ 
        path: routePoints, 
        strokeOpacity: 1.0, 
        strokeWeight: 2, 
        map: map, 
       }); 
      } 
     } 

removeLines()函数如下。我已经尝试了许多不同版本的这个函数(while循环,routePoints.pop(),将routePoints.length设置为0),但是没有任何东西已经清除了MVCArray。通过这种方式正确显示多段线,但是一旦用户改变了他们的选择,我需要将先前的多段线从地图中移除。提前致谢。

function removeLines() { 
     if (routePoints) { 
      for (var i=0; i < routePoints.length; i++) { 
       routePoints.removeAt(i); 
      } 
     } 
    } 

回答

2

所以routePoints只是一个LatLng对象的数组,而不是单独的多段线。我想你可能需要一个单独的数组作为多段线,然后你可以循环去除它们。
如果你想删除可见的多段线,你可以调用setMap()函数,传递它null

routePoints = new google.maps.MVCArray(); 
var polylines = []; // new array for the polylines, needs to be a global variable 

xmlhttp.onreadystatechange=function() { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) { 
     markersArray = eval("(" + xmlhttp.responseText + ")"); 
     removeLines(); 
     for (var i = 0; i < markersArray.length; i++) { 
      var address = new google.maps.LatLng(markersArray[i][0], markersArray[i][1]); 
      routePoints.insertAt(routePoints.length, address); 
     } 
     routePath = new google.maps.Polyline({ 
      path: routePoints, 
      strokeOpacity: 1.0, 
      strokeWeight: 2, 
      map: map, 
     }); 

     // add the polyline to the array 
     polylines.push(routePath); 
    } 
} 

function removeLines() { 
    for (var i=0; i < polylines.length; i++) { 
     polylines[i].setMap(null); 
    } 

    // you probably then want to empty out your array as well 
    polylines = []; 

    // not sure you'll require this at this point, but if you want to also clear out your array of coordinates... 
    routePoints.clear(); 
} 
+0

感谢您的输入,但是这是行不通的。 Firebug显示“polylines.setMap不是函数”的错误。当我隐藏polylines.setMap(null)行时,我在Firebug中没有收到任何错误消息,并且地图返回工作状态,但是在新的用户选择时仍然不会删除多义线。 – scrolls 2012-01-30 14:09:58

+0

我的错误,现在尝试更新代码 – duncan 2012-01-30 14:39:32

+0

作品完美,非常感谢。 – scrolls 2012-01-30 14:53:02

2

删除所有都是MVCArray元素:

routePoints.clear(); 
相关问题