Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leaflet Control [draft] #1662

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
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)