AssertionError: Assertion failed: length of coordinate array should match stride

AssertionError: Assertion failed: length of coordinate array should match stride

我试图在我的 OpenLayers 3 地图中创建一些多边形,但出现以下错误:

AssertionError: Assertion failed: length of coordinate array should match stride

我使用的代码如下:

var geometry = new ol.geom.Polygon([
  [10.689697265625, -25.0927734375],
  [34.595947265625, -20.1708984375],
  [38.814697265625, -35.6396484375],
  [13.502197265625, -39.1552734375],
  [10.689697265625, -25.0927734375]
], "XY");

geometry.transform('EPSG:4326', 'EPSG:3857');

var vectorLayer = new ol.layer.Vector({
    map: this.map,
    source: new ol.source.Vector({
        features: [new ol.Feature({
            geometry: geometry
        })]
    })
});

我一直在努力寻找解决方案,在 Internet 上找不到任何关于错误本身的参考资料(OpenLayers 的源代码除外)。

我找到了解决办法,但我把它贴在这里供参考,以防以后有人遇到同样的问题。

那么,这是什么原因?

经过大量挖掘,我意识到多边形的定义需要一组额外的括号:

var geometry = new ol.geom.Polygon([ [
  [10.689697265625, -25.0927734375],
  [34.595947265625, -20.1708984375],
  [38.814697265625, -35.6396484375],
  [13.502197265625, -39.1552734375],
  [10.689697265625, -25.0927734375]
] ]);

geometry.transform('EPSG:4326', 'EPSG:3857');

var vectorLayer = new ol.layer.Vector({
    map: this.map,
    source: new ol.source.Vector({
        features: [new ol.Feature({
            geometry: geometry
        })]
    })
});

这有效!

这是终于启发了我的jsfiddle:http://jsfiddle.net/q8s2z/111/

documentation所述,坐标参数是ol.Coordinate的数组(也是数组)的数组。

同样,MultiPolygon 将定义为:

var geometry = new ol.geom.MultiPolygon([ [
  [10.689697265625, -25.0927734375],
  [34.595947265625, -20.1708984375],
  [38.814697265625, -35.6396484375],
  [13.502197265625, -39.1552734375],
  [10.689697265625, -25.0927734375]
], [
  [10.689697265625, -25.0927734375],
  [34.595947265625, -20.1708984375],
  [38.814697265625, -35.6396484375],
  [13.502197265625, -39.1552734375],
  [10.689697265625, -25.0927734375]
] ]);