1
votes

I am using OpenLayers Version: v3.13.0 and i am trying to export all fetaures in my layer. my code is as follows

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);

I am getting error "Uncaught TypeError: Cannot read property 'length' of undefined"

When i console the variable newfeatures I am getting all drawn features in an array. Please help me in resolving this

3
i modified the writeFeatures(newfeatures); to writeFeatures(newfeatures[0]); then error disapperared but feature is not converted to xml output as follows <kml xmlns="opengis.net/kml/2.2" xmlns:gx="google.com/kml/ext/2.2" xmlns:xsi="w3.org/2001/XMLSchema-instance" xsi:schemaLocation="opengis.net/kml/2.2 developers.google.com/kml/schema/kml22gx.xsd"> - Deepu

3 Answers

3
votes

You can export the features without cloning and transforming them manually. Replace your whole code above with

var features = layer.getSource().getFeatures();
var string = new format.KML().writeFeatures(features, {
  featureProjection: map.getView().getProjection()
});

The above snippet assumes that the map variable holds your ol.Map instance.

Note that there are no maxDepth, internalProjection and externalProjection options on ol.format.KML.

2
votes

Write features using 3857 projection

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

The direct kml conversion not worked. So first feature converted to GEOJSON. Then this GEOJSON converted to kml using following library .

https://github.com/mapbox/tokml