mapbox / tokml

Convert GeoJSON to KML.
http://mapbox.github.io/tokml/
BSD 2-Clause "Simplified" License
189 stars 91 forks source link

Further Documentation/examples? #34

Closed Jonkat323 closed 6 years ago

Jonkat323 commented 6 years ago

Hi all,

Is there any more documentation or examples available online? I am still quite new to Leaflet so I could do with all the help I can get. I currently have a map using Leaflet.Draw with some export feature code. However, the featureGroup is saved as a geoJSON and it would be ideal if this could be converted to .kml before downloading.

The export code is as follows:

       `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');
        }`
kriscarle commented 6 years ago

You'll need to add this library to your webpage to use it.

1) Download the file from https://raw.github.com/mapbox/tokml/master/tokml.js 2) Then add it your your web page with a script tag

<script type="text/javascript" src="tokml.js"></script>

3) add it in your code setting the correct mime type and file extension. What the Leaflet example is doing is formatting the data as a Data URL https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

document.getElementById('export').onclick = function(e) {
        // Extract GeoJson from featureGroup
        var data = featureGroup.toGeoJSON();
        var kml = tokml(data)
        // Convert to dataURL format
        var convertedData = 'application/vnd.google-earth.kml+xml;charset=utf-8,' + encodeURIComponent(xml);

        // Create export
        document.getElementById('export').setAttribute('href', 'data:' + convertedData);
        document.getElementById('export').setAttribute('download','data.kml');
}
Jonkat323 commented 6 years ago

Thanks so much for your help! The part I was going wrong with was definitely the correct mime type. However, the conversion and export still wasn't working, but I changed "(xml);" to "(kml);" at the end of the conversion line and now everything is working perfectly.