|
3 | 3 | from branca.element import CssLink, Element, Figure, JavascriptLink, MacroElement |
4 | 4 | from jinja2 import Template |
5 | 5 |
|
| 6 | +from folium.utilities import JsCode |
| 7 | + |
6 | 8 |
|
7 | 9 | class JSCSSMixin(Element): |
8 | 10 | """Render links to external Javascript and CSS resources.""" |
@@ -46,6 +48,80 @@ def _add_link(self, name: str, url: str, default_list: List[Tuple[str, str]]): |
46 | 48 | default_list.append((name, url)) |
47 | 49 |
|
48 | 50 |
|
| 51 | +class EventHandler(MacroElement): |
| 52 | + ''' |
| 53 | + Add javascript event handlers. |
| 54 | +
|
| 55 | + Examples |
| 56 | + -------- |
| 57 | + >>> import folium |
| 58 | + >>> from folium.utilities import JsCode |
| 59 | + >>> |
| 60 | + >>> m = folium.Map() |
| 61 | + >>> |
| 62 | + >>> geo_json_data = { |
| 63 | + ... "type": "FeatureCollection", |
| 64 | + ... "features": [ |
| 65 | + ... { |
| 66 | + ... "type": "Feature", |
| 67 | + ... "geometry": { |
| 68 | + ... "type": "Polygon", |
| 69 | + ... "coordinates": [ |
| 70 | + ... [ |
| 71 | + ... [100.0, 0.0], |
| 72 | + ... [101.0, 0.0], |
| 73 | + ... [101.0, 1.0], |
| 74 | + ... [100.0, 1.0], |
| 75 | + ... [100.0, 0.0], |
| 76 | + ... ] |
| 77 | + ... ], |
| 78 | + ... }, |
| 79 | + ... "properties": {"prop1": {"title": "Somewhere on Sumatra"}}, |
| 80 | + ... } |
| 81 | + ... ], |
| 82 | + ... } |
| 83 | + >>> |
| 84 | + >>> g = folium.GeoJson(geo_json_data).add_to(m) |
| 85 | + >>> |
| 86 | + >>> highlight = JsCode( |
| 87 | + ... """ |
| 88 | + ... function highlight(e) { |
| 89 | + ... e.target.original_color = e.layer.options.color; |
| 90 | + ... e.target.setStyle({ color: "green" }); |
| 91 | + ... } |
| 92 | + ... """ |
| 93 | + ... ) |
| 94 | + >>> |
| 95 | + >>> reset = JsCode( |
| 96 | + ... """ |
| 97 | + ... function reset(e) { |
| 98 | + ... e.target.setStyle({ color: e.target.original_color }); |
| 99 | + ... } |
| 100 | + ... """ |
| 101 | + ... ) |
| 102 | + >>> |
| 103 | + >>> g.add_child(EventHandler("mouseover", highlight)) |
| 104 | + >>> g.add_child(EventHandler("mouseout", reset)) |
| 105 | + ''' |
| 106 | + |
| 107 | + _template = Template( |
| 108 | + """ |
| 109 | + {% macro script(this, kwargs) %} |
| 110 | + {{ this._parent.get_name()}}.on( |
| 111 | + {{ this.event|tojson}}, |
| 112 | + {{ this.handler.js_code }} |
| 113 | + ); |
| 114 | + {% endmacro %} |
| 115 | + """ |
| 116 | + ) |
| 117 | + |
| 118 | + def __init__(self, event: str, handler: JsCode): |
| 119 | + super().__init__() |
| 120 | + self._name = "EventHandler" |
| 121 | + self.event = event |
| 122 | + self.handler = handler |
| 123 | + |
| 124 | + |
49 | 125 | class ElementAddToElement(MacroElement): |
50 | 126 | """Abstract class to add an element to another element.""" |
51 | 127 |
|
|
0 commit comments