Skip to content

Commit

Permalink
Add event handlers to the draw plugin
Browse files Browse the repository at this point in the history
This makes the draw plugin more dynamic. It allows the user
to add `JsCode` event handlers to the generated layers.
  • Loading branch information
hansthen committed Oct 5, 2024
1 parent dc84732 commit a2c9292
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions folium/plugins/draw.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


class Draw(JSCSSMixin, MacroElement):
"""
'''
Vector drawing and editing plugin for Leaflet.
Parameters
Expand All @@ -25,22 +25,35 @@ class Draw(JSCSSMixin, MacroElement):
edit_options : dict, optional
The options used to configure the edit toolbar. See
https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html#editpolyoptions
on : dict, optional
Event handlers to attach to the created layer. Pass a mapping from the
names of the events to their `JsCode` handlers.
Examples
--------
>>> m = folium.Map()
>>> Draw(
... export=True,
... filename="my_data.geojson",
... show_geometry_on_click=False,
... position="topleft",
... draw_options={"polyline": {"allowIntersection": False}},
... edit_options={"poly": {"allowIntersection": False}},
... on={
... "click": JsCode(
... """
... function(event) {
... alert(JSON.stringify(this.toGeoJSON()));
... }
... """
... )
... },
... ).add_to(m)
For more info please check
https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html
"""
'''

_template = Template(
"""
Expand Down Expand Up @@ -68,11 +81,15 @@ class Draw(JSCSSMixin, MacroElement):
console.log(coords);
});
{%- endif %}
{%- for event, handler in this.on.items() %}
layer.on(
"{{event}}",
{{handler}}
);
{%- endfor %}
drawnItems_{{ this.get_name() }}.addLayer(layer);
});
{{ this._parent.get_name() }}.on('draw:created', function(e) {
drawnItems_{{ this.get_name() }}.addLayer(e.layer);
});
{% if this.export %}
document.getElementById('export').onclick = function(e) {
var data = drawnItems_{{ this.get_name() }}.toGeoJSON();
Expand Down Expand Up @@ -111,6 +128,7 @@ def __init__(
show_geometry_on_click=True,
draw_options=None,
edit_options=None,
on=None,
):
super().__init__()
self._name = "DrawControl"
Expand All @@ -120,6 +138,7 @@ def __init__(
self.show_geometry_on_click = show_geometry_on_click
self.draw_options = draw_options or {}
self.edit_options = edit_options or {}
self.on = on or {}

def render(self, **kwargs):
super().render(**kwargs)
Expand Down

0 comments on commit a2c9292

Please sign in to comment.