下载后将geoJson文件内容添加到矢量图层

Add contents of geoJson file to vector layer after download

我想从服务下载 geoJson 格式的要素,然后将其中的要素添加到地图上的新图层。我可以下载这些功能,但我不知道如何在下载后将它们添加到地图中。 我不想让 OL 直接从 url 读取文件,如我能找到的每个示例所示,因为我想更多地控制何时下载功能或如果由于某种原因下载失败该怎么办. 我正在尝试这个(数据包含我的 geoJson featurecollection):

var nwLayer = new ol.layer.Vector({
    title: 'My Title',
    source: new ol.source.Vector({
        features: data.features,
        format: new ol.format.GeoJSON()
    }),
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill( { color: "yellow" } )
        })
    })
} );
map.addLayer(nwLayer);

这会导致 ol 库中某处出错,显然 ol 特征类型与 geoJson 特征不同,它需要一个 getId() 函数。 我还尝试将数据作为一个整体添加:

features: data,

这个完全没有视觉效果。 我该怎么做?

你是对的,OpenLayer 要素不是 GeoJSON 要素对象。要将 GeoJSON 转换为 OpenLayers 功能,请使用 ol.format.GeoJSONreadFeatures 方法。

您的示例代码的其余部分:

var nwLayer = new ol.layer.Vector({
    title: 'My Title',
    source: new ol.source.Vector({
        features: (new ol.format.GeoJSON()).readFeatures(data)
    }),
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill( { color: "yellow" } )
        })
    })
});
map.addLayer(nwLayer);