如何将 GeoJSON 多边形特征添加到 OpenLayers 5 中的矢量源

How to add a GeoJSON polygon feature to a vector source in OpenLayers 5

我对这个问题看起来多么简单感到尴尬,但我似乎无法弄清楚如何简单地将 GeoJSON 多边形特征添加到矢量源。

我使用的是 OpenLayers 5,到目前为止,我一直在为要添加到地图的每个要素创建单独的源和图层。原因是我需要能够打开和关闭单个多边形的可见性,这在当时似乎是最好的方法。这起初有效,但我确信这不是最佳实践 - 实际上我正在为 200 个多边形创建 200 个图层和 200 个源。我更愿意创建一个图层,该图层使用一个包含这 200 个多边形的源。

这是我目前拥有的:

window["srcCells"] = new ol.source.Vector({});
window["ftr1"] = new ol.Feature({
    geometry: new ol.geom.Polygon({ // <--- this is where I'm getting an error
        coordinates: geometry.coordinates[0]
    })
});
window["srcCells"].addFeature(window["ftr1"]);
window["lyrCells"] = new ol.layer.Vector({
    name: "lyrCells",
    source: window["srcCells"],
    visible: true,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
        color: 'rgba(255, 255, 255, 1)',
        width: 0.5
    }),
    fill: new ol.style.Fill({
        color: 'rgba(255, 255, 255, 0)'
    }),
    text: new ol.style.Text({
        font: '11px Roboto',
        overflow: false,
        fill: new ol.style.Fill({
            color: '#fff'
        }),
        stroke: new ol.style.Stroke({
            color: '#333',
            width: 2
        })
    })
    })
});
map.addLayer(window["lyrCells"]);

console.dir(geometry.coordinates[0]); 给出以下内容:

0: (3) [140.9528856796365, -37.00284635019008, 111.304]
1: (3) [140.9536707180603, -37.00304972058393, 113.03]
2: (3) [140.9537622719694, -37.00307250872015, 110.607]
3: (3) [140.95383548835147, -37.003105295678026, 110.64]
4: (3) [140.95393795398604, -37.003149857783384, 110.26276070403628]
5: (3) [140.95586925648476, -37.00401679761869, 111.192]
6: (3) [140.95644098404094, -37.00388629902322, 110.38710718081241]
7: (3) [140.95644582710668, -37.0051300157363, 111.17174176388276]
8: (3) [140.9528945167084, -37.00514320603378, 110.9445749409575]
9: (3) [140.95289318042316, -37.004769323489825, 113.688]

在上面代码的第三行(我指出的地方),我收到了这个错误:

SimpleGeometry.js:187 Uncaught TypeError: Cannot read property 'length' of undefined
    at e.setLayout (SimpleGeometry.js:187)
    at e.setCoordinates (Polygon.js:313)
    at new e (Polygon.js:80)

geometry.coordinates[0] 看起来像一个开放的线串。要将其用作多边形,您需要关闭环,并且由于多边形是线性环的数组,因此用 [] 括起来。坐标也是构造函数的第一个参数,而不是一个选项:

geometry: new ol.geom.Polygon(
     [ geometry.coordinates[0].concat([geometry.coordinates[0][0]]) ]
)

或者,您可能需要检查您的数据是多边形还是线串,并在适当的地方使用新的 ol.geom.LineString