无法使用Google Maps API V3删除MVCArray / Polylines

时间:2012-01-30 03:11:10

标签: javascript google-maps google-maps-api-3

我有一个MVCArray来存储我的折线路径,但我需要在用户更改其选择时清除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 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:2)

删除所有mvcarray元素:

routePoints.clear();