Leaflet – Convert GeoJSON to KML with Leaflet.Draw

convertgeojsonkmlleafletleaflet-draw

I have made a map using the Leaflet Draw plugin which allows the user to download their drawn items. These drawnItems are exported as GeoJSON using the following code from here:

document.getElementById('export').onclick = function(e) {
// Extract GeoJSON from featureGroup
var data = featureGroup.toGeoJSON();

// Stringify the GeoJSON
var convertedData = 'text/json;charset=utf-8,' + 
encodeURIComponent(JSON.stringify(data));

// Create export
document.getElementById('export').setAttribute('href', 'data:' + convertedData);      
document.getElementById('export').setAttribute('download','data.geojson');
}

This works perfectly, but it would be even more ideal if the GeoJSON was converted to .kml before being exported. I am aware of the toKml plugin but I am struggling to get it to work (I am still quite new to all of this). Where would I add:

var kml = tokml(geojsonObject);

And I am sure I would have to edit the //create export part of the GeoJSON code

Best Answer

var data = featureGroup.toGeoJSON();
var kml = tokml(data);

var convertedData = 'application/xml;charset=utf-8,' + 
encodeURIComponent(kml);

// if you want to use the official MIME type for KML
// var convertedData = 'application/vnd.google-earth.kml+xml;charset=utf-8,'+ 
// encodeURIComponent(kml);

document.getElementById('export').setAttribute('href', 'data:' + convertedData); 
document.getElementById('export').setAttribute('download', 'data.kml');
Related Question