Openlayers 3 KML 导出 writeFeatures() 不工作

Openlayers 3 KML export writeFeatures() not working

我使用的是 OpenLayers 版本:v3.13.0,我正在尝试导出图层中的所有特征。我的代码如下

var projection = ol.proj.get('EPSG:3857');
    var format = new ol.format.KML({
        'maxDepth': 10,
        'extractStyles': true,
        'internalProjection': projection,
        'externalProjection': projection
    });
var newfeatures = [];
var vectorSource = layer.getSource();
vectorSource.forEachFeature(function(feature) {
        var clone = feature.clone();
        clone.setId(feature.getId());  // clone does not set the id
        clone.getGeometry().transform(projection, 'EPSG:4326');
        newfeatures.push(clone);
});
//console.log(newfeatures);
var string = new ol.format.KML().writeFeatures(newfeatures);
//console.log(string);

我遇到错误 "Uncaught TypeError: Cannot read property 'length' of undefined"

当我控制变量 newfeatures 时,我得到了一个数组中的所有绘制特征。请帮我解决这个问题

您可以导出特征而无需手动克隆和转换它们。用

替换上面的整个代码
var features = layer.getSource().getFeatures();
var string = new format.KML().writeFeatures(features, {
  featureProjection: map.getView().getProjection()
});

上面的代码片段假定 map 变量包含您的 ol.Map 实例。

请注意 ol.format.KML 上没有 maxDepthinternalProjectionexternalProjection 选项。

直接 kml 转换无效。所以首先将特征转换为 GEOJSON。 然后使用以下库将此 GEOJSON 转换为 kml。

https://github.com/mapbox/tokml

使用 3857 投影写入特征

function GetKMLFromFeatures(features) {
    var format = new ol.format.KML();
    var kml = format.writeFeatures(features, {featureProjection: 'EPSG:3857'});
    return kml;
}