diff --git a/folium/features.py b/folium/features.py index 8385b3d46e..4fced617bb 100644 --- a/folium/features.py +++ b/folium/features.py @@ -21,6 +21,7 @@ from folium.utilities import ( _parse_size, camelize, + escape_backticks, get_bounds, get_obj_in_upper_tree, image_to_url, @@ -1899,3 +1900,47 @@ def __init__( self.add_child( PolyLine(val, color=key, weight=weight, opacity=opacity) ) # noqa + + +class CustomControl(MacroElement): + """Display static html and switch together with parent layer.""" + + _template = Template( + """ + {% macro script(this, kwargs) %} + + {{ this.get_name() }} = L.control({ + position: "{{ this.position }}", + }); + {{ this.get_name() }}.onAdd = function(map) { + let div = L.DomUtil.create('div'); + 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, position="bottomleft"): + super().__init__() + self._name = "custom_control" + 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)