Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from folium.utilities import (
_parse_size,
camelize,
escape_backticks,
get_bounds,
get_obj_in_upper_tree,
image_to_url,
Expand Down Expand Up @@ -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)