javascriptleafletgisleaflet.draw

Leaflet.draw mapping: How to initiate the draw function without toolbar?


For anyone experienced with leaflet or leaflet.draw plugin:

I want to initiate drawing a polygon without using the toolbar from leaflet.draw. I've managed to find the property that allows editing without using the toolbar (layer.editing.enable();) by searching online (it's not in the main documentation). I can't seem to find how to begin drawing a polygon without the toolbar button. Any help would be much appreciated!

Thank you :)


Solution

  • This simple code works for me:

    new L.Draw.Polyline(map, drawControl.options.polyline).enable();
    

    Just put it into the onclick handler of your custom button (or wherever you want).

    The variables map and drawControl are references to your leaflet map and draw control.

    Diving into the source code (leaflet.draw-src.js) you can find the functions to draw the other elements and to edit or delete them.

    new L.Draw.Polygon(map, drawControl.options.polygon).enable()
    new L.Draw.Rectangle(map, drawControl.options.rectangle).enable()
    new L.Draw.Circle(map, drawControl.options.circle).enable()
    new L.Draw.Marker(map, drawControl.options.marker).enable()
    
    new L.EditToolbar.Edit(map, {
                    featureGroup: drawControl.options.featureGroup,
                    selectedPathOptions: drawControl.options.edit.selectedPathOptions
                })
    new L.EditToolbar.Delete(map, {
                    featureGroup: drawControl.options.featureGroup
                })
    

    I hope this will be useful for you too.

    EDIT: The L.EditToolbar.Edit and L.EditToolbar.Delete classes expose the following useful methods: