Search code examples
javascriptleafletkmlleaflet.draw

Adding KML file to leaflet-draw drawnItems


I'm trying to import a KML file into leaflet and make it editable for leaflet-draw. I'm using leaflet-omnivore to import the KML.

<script src='https://api.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script>
var kmlFile = omnivore.kml('Point.kml')

If I add the kmlFile to map it works perfectly, but in order to make the shapes editable I need to add the layer to drawnItems

 var drawnItems = new L.FeatureGroup();  
 omnivore.kml('Point.kml').addTo(drawnItems);

However I get an error message:

TypeError: i.editing is undefined.

And when I try to access the layers coordinates to create objects by myself and add them to drawnItems, I can't seem to do so, since I can't find a way to access the object coordinates.

When I try to access the layers they appear empty

console.dir(omnivore.kml('Point.kml').getLayers());

But when I inspect the omnivore kml object I can see that _layers contains the objects and coordinates.

console.dir(omnivore.kml('Point.kml'));

But when executing the getLayers method, the layers array appears empty.

Any suggestions?


Solution

  • Please note that Leaflet omnivore plugin provides asynchronous methods, since it has to download files before it can parse them and create Leaflet layers.

    For more details about asynchronous tasks in JavaScript, please refer to: How do I return the response from an asynchronous call?

    That is why your Layer Group looks empty when you try to read it right away.

    If you need to perform some operations only once the data is correctly downloaded and converted to Leaflet layers, use the .on("ready", fn) syntax, as explained in the plugin README.

    As for adding the resulting layers into a Feature Group (for later use with Leaflet.draw plugin), note that you can directly provide your Feature Group as 3rd argument of omnivore.kml().