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

Add Custom Control #1953

Closed
wants to merge 1 commit into from
Closed
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
70 changes: 70 additions & 0 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 %}
<style>
.class_{{this.get_name()}} {{ "{" }} {{this.style}} {{ "}" }}
</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)