2012-01-30 84 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(); 
相關問題