Skip to content

Commit 5a7a173

Browse files
authored
Add event handlers to the Draw plugin (#2000)
* 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
1 parent 806f697 commit 5a7a173

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

folium/plugins/draw.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66

77
class Draw(JSCSSMixin, MacroElement):
8-
"""
8+
'''
99
Vector drawing and editing plugin for Leaflet.
1010
1111
Parameters
@@ -28,22 +28,35 @@ class Draw(JSCSSMixin, MacroElement):
2828
edit_options : dict, optional
2929
The options used to configure the edit toolbar. See
3030
https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html#editpolyoptions
31+
on : dict, optional
32+
Event handlers to attach to the created layer. Pass a mapping from the
33+
names of the events to their `JsCode` handlers.
3134
3235
Examples
3336
--------
3437
>>> m = folium.Map()
3538
>>> Draw(
3639
... export=True,
3740
... filename="my_data.geojson",
41+
... show_geometry_on_click=False,
3842
... position="topleft",
3943
... draw_options={"polyline": {"allowIntersection": False}},
4044
... edit_options={"poly": {"allowIntersection": False}},
45+
... on={
46+
... "click": JsCode(
47+
... """
48+
... function(event) {
49+
... alert(JSON.stringify(this.toGeoJSON()));
50+
... }
51+
... """
52+
... )
53+
... },
4154
... ).add_to(m)
4255
4356
For more info please check
4457
https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html
4558
46-
"""
59+
'''
4760

4861
_template = Template(
4962
"""
@@ -78,11 +91,19 @@ class Draw(JSCSSMixin, MacroElement):
7891
console.log(coords);
7992
});
8093
{%- endif %}
94+
95+
{%- for event, handler in this.on.items() %}
96+
layer.on(
97+
"{{event}}",
98+
{{handler}}
99+
);
100+
{%- endfor %}
81101
drawnItems_{{ this.get_name() }}.addLayer(layer);
82102
});
83103
{{ this._parent.get_name() }}.on('draw:created', function(e) {
84104
drawnItems_{{ this.get_name() }}.addLayer(e.layer);
85105
});
106+
86107
{% if this.export %}
87108
document.getElementById('export').onclick = function(e) {
88109
var data = drawnItems_{{ this.get_name() }}.toGeoJSON();
@@ -122,6 +143,7 @@ def __init__(
122143
show_geometry_on_click=True,
123144
draw_options=None,
124145
edit_options=None,
146+
on=None,
125147
):
126148
super().__init__()
127149
self._name = "DrawControl"
@@ -132,6 +154,7 @@ def __init__(
132154
self.show_geometry_on_click = show_geometry_on_click
133155
self.draw_options = draw_options or {}
134156
self.edit_options = edit_options or {}
157+
self.on = on or {}
135158

136159
def render(self, **kwargs):
137160
super().render(**kwargs)

0 commit comments

Comments
 (0)