1

我对javascript有一个非常奇怪的问题。我用 OpenLayers 和 OSM 的 mapdata 制作了一张地图。每次我绘制一个特征(点或线)时,我都会在草图完成时触发一个函数,redrawFeatures主要是为了分割线并给每条线一个起点和一个终点。到目前为止一切正常,但我也想将绘制的点(和线)从地图投影(EPSG:900913)转换为显示投影(EPSG:4326)并且存在问题。以下代码是函数:

var pointsOnMap = [];
var linesOnMap = [];

function redrawFeatures(e) {
    var vert = e.feature.geometry.getVertices();
    var points = [];
    var pointFeatures = [];
    var lineFeatures = [];

    for (var i = 0; i < vert.length; i++) {
        var point       = new OpenLayers.Geometry.Point(vert[i].x, vert[i].y);

        points.push(point);
        alert(points[i].x + ', ' + points[i].y);
        pointFeatures.push(new OpenLayers.Feature.Vector(point));
        alert(points[i].x + ', ' + points[i].y);
        pointsOnMap.push(point.transform(new OpenLayers.Projection("EPSG:900913"),
                                         new OpenLayers.Projection("EPSG:4326")));
        alert(points[i].x + ', ' + points[i].y);
        if (i >= 1) {
            var line = new OpenLayers.Geometry.LineString([points[i-1], points[i]]);

            lineFeatures.push(new OpenLayers.Feature.Vector(line));
            linesOnMap.push(line.transform(new OpenLayers.Projection("EPSG:900913"),
                                           new OpenLayers.Projection("EPSG:4326")));
        }
    }

    draw.destroyFeatures([e.feature]);
    draw.addFeatures(lineFeatures);
    draw.addFeatures(pointFeatures);

}

命名的变量draw是我绘制的图层。

我从事件中确定坐标,创建一个新点(第 11 行)并将它们保存到一个数组中(第 13 行)。将同一点转换为特征并将其保存到另一个数组中(第 15 行)在名为 的第一个数组的先前保存的值中points。我提醒保存的坐标三次的值,这是我得到但不明白的:

警报 1(第 14 行)没错,我得到了点的坐标

警报 2(第 16 行)仍然正确(与第一个相同)

警报 3(第 19 行)现在错误了!我像以前一样警告相同的变量,但在转换后point的值points[i]也无缘无故地改变了。

有什么我没有意识到的错误吗?

4

2 回答 2

2

似乎转换函数就地运行,并修改了现有point数据。如果要保留以前的值,则应该克隆该点,然后对其进行操作

clone = point.clone();
于 2012-11-05T12:37:45.273 回答
1

在 JavaScript 中:

var a = [1,2,3]
var b = a; //Here you are actually copying the reference of a
b.push(4); //This will also add 4 to a...a = [1,2,3,4] now
//In order to actually copy the array instead of reference u need to clone it as follows
var c = a.slice(); //creates a clone of a
c.push(5); // c = [1,2,3,4,5] and a = [1,2,3,4]
于 2012-11-05T12:36:54.570 回答