diff --git a/folium/features.py b/folium/features.py index bca5c6d707..ca58f33988 100644 --- a/folium/features.py +++ b/folium/features.py @@ -1973,3 +1973,73 @@ def __init__( out.setdefault(cm(color), []).append([[lat1, lng1], [lat2, lng2]]) for key, val in out.items(): self.add_child(PolyLine(val, color=key, weight=weight, opacity=opacity)) + + +class CustomControl(MacroElement): + """Display static html and switch together with parent layer. + + Parameters + ---------- + html: str + The html to be rendered + style: str + The css style to be applied to this element + position: str + One of "bottomright", "bottomleft", "topright", "topleft" + + Examples + -------- + >>> m = folium.Map( + ... location=[46.603354, 1.8883335], zoom_control=False, zoom_start=5 + ... ) + >>> CustomControl("This is my custom control", position="topleft").add_to(m) + """ + + _template = Template( + """ + {% macro header(this,kwargs) %} + {%- if this.style %} + + {%- endif %} + {% endmacro %} + + {% macro script(this, kwargs) %} + + var {{ this.get_name() }} = L.control({ + position: "{{ this.position }}", + }); + {{ this.get_name() }}.onAdd = function(map) { + let div = L.DomUtil.create('div', 'class_{{this.get_name()}}'); + div.innerHTML = `{{ this.html }}`; + return div; + } + {{ this.get_name() }}.addTo({{ this.parent_map.get_name() }}); + + {%- if this.switch %} + {{ this._parent.get_name() }}.on('add', function(e) { + {{ this.get_name() }}.addTo({{ this.parent_map.get_name() }}); + }); + {{ this._parent.get_name() }}.on('remove', function(e) { + e.target._map.removeControl({{ this.get_name() }}); + }); + {%- endif %} + + {% endmacro %} + """ + ) + + def __init__(self, html, style=None, position="bottomleft"): + super().__init__() + self._name = "custom_control" + self.style = style + self.html = escape_backticks(html) + self.position = position + self.parent_map = None + self.switch = None + + def render(self, **kwargs): + self.parent_map = get_obj_in_upper_tree(self, Map) + self.switch = isinstance(self._parent, Layer) and self._parent.control + super().render(**kwargs)