Skip to content

Commit

Permalink
Add event handlers to the Draw plugin (#2000)
Browse files Browse the repository at this point in the history
* Add event handlers to the draw plugin

This makes the draw plugin more dynamic. It allows the user
to add `JsCode` event handlers to the generated layers.

* Removed numpy version fix
  • Loading branch information
hansthen authored Oct 18, 2024
1 parent 806f697 commit 5a7a173
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 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 @@ -28,22 +28,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 @@ -78,11 +91,19 @@ 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 @@ -122,6 +143,7 @@ def __init__(
show_geometry_on_click=True,
draw_options=None,
edit_options=None,
on=None,
):
super().__init__()
self._name = "DrawControl"
Expand All @@ -132,6 +154,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 5a7a173

Please sign in to comment.