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 a custom container to the realtime plugin #1869

Merged
merged 7 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions docs/user_guide/plugins/realtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,27 @@ Realtime(

m
```

## Using a MarkerCluster as a container

The subway stations in the previous example are not easy to distinguish at lower zoom levels.
It is possible to use a custom container for the GeoJson. In this example we use a MarkerCluster.
```{code-cell} ipython3
import folium
from folium import JsCode
from folium.plugins import Realtime, MarkerCluster

m = folium.Map(location=[40.73, -73.94], zoom_start=12)
source = "https://raw.githubusercontent.com/python-visualization/folium-example-data/main/subway_stations.geojson"

container = MarkerCluster().add_to(m)
Realtime(
source,
get_feature_id=JsCode("(f) => { return f.properties.objectid }"),
point_to_layer=JsCode("(f, latlng) => { return L.circleMarker(latlng, {radius: 8, fillOpacity: 0.2})}"),
container=container,
interval=10000,
).add_to(m)

m
```
16 changes: 14 additions & 2 deletions folium/plugins/realtime.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from typing import Union
from typing import Optional, Union

from branca.element import MacroElement
from jinja2 import Template

from folium.elements import JSCSSMixin
from folium.map import Layer
from folium.utilities import JsCode, camelize, parse_options


Expand Down Expand Up @@ -41,7 +42,11 @@ class Realtime(JSCSSMixin, MacroElement):
remove_missing: bool, default False
Should missing features between updates been automatically
removed from the layer

container: Layer, default GeoJson
The container will typically be a `FeatureGroup`, `MarkerCluster` or
`GeoJson`, but it can be anything that generates a javascript
L.LayerGroup object, i.e. something that has the methods
`addLayer` and `removeLayer`.

Other keyword arguments are passed to the GeoJson layer, so you can pass
`style`, `point_to_layer` and/or `on_each_feature`. Make sure to wrap
Expand Down Expand Up @@ -70,6 +75,11 @@ class Realtime(JSCSSMixin, MacroElement):
{{ this.get_name() }}_options["{{key}}"] = {{ value }};
{% endfor %}

{% if this.container -%}
{{ this.get_name() }}_options["container"]
= {{ this.container.get_name() }};
{% endif -%}

var {{ this.get_name() }} = new L.realtime(
{% if this.src is string or this.src is mapping -%}
{{ this.src|tojson }},
Expand Down Expand Up @@ -99,11 +109,13 @@ def __init__(
get_feature_id: Union[JsCode, str, None] = None,
update_feature: Union[JsCode, str, None] = None,
remove_missing: bool = False,
container: Optional[Layer] = None,
hansthen marked this conversation as resolved.
Show resolved Hide resolved
hansthen marked this conversation as resolved.
Show resolved Hide resolved
**kwargs
):
super().__init__()
self._name = "Realtime"
self.src = source
self.container = container

kwargs["start"] = start
kwargs["interval"] = interval
Expand Down
66 changes: 66 additions & 0 deletions tests/plugins/test_realtime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""
Test Realtime
------------------
"""

from jinja2 import Template

import folium
from folium.plugins import MarkerCluster, Realtime
from folium.utilities import JsCode, normalize


def test_realtime():
m = folium.Map(location=[40.73, -73.94], zoom_start=12)
source = "https://raw.githubusercontent.com/python-visualization/folium-example-data/main/subway_stations.geojson"

container = MarkerCluster().add_to(m)

rt = Realtime(
source,
get_feature_id=JsCode("(f) => { return f.properties.objectid }"),
point_to_layer=JsCode(
"(f, latlng) => { return L.circleMarker(latlng, {radius: 8, fillOpacity: 0.2})}"
),
container=container,
interval=10000,
)
rt.add_to(m)

tmpl_for_expected = Template(
"""
{% macro script(this, kwargs) %}
var {{ this.get_name() }}_options = {{ this.options|tojson }};
{% for key, value in this.functions.items() %}
{{ this.get_name() }}_options["{{key}}"] = {{ value }};
{% endfor %}

{% if this.container -%}
{{ this.get_name() }}_options["container"]
= {{ this.container.get_name() }};
{% endif -%}

var {{ this.get_name() }} = new L.realtime(
{% if this.src is string or this.src is mapping -%}
{{ this.src|tojson }},
{% else -%}
{{ this.src.js_code }},
{% endif -%}
{{ this.get_name() }}_options
);
{{ this._parent.get_name() }}.addLayer(
{{ this.get_name() }}._container);
{% endmacro %}
"""
)
expected = normalize(tmpl_for_expected.render(this=rt))

out = normalize(m._parent.render())

# We verify that imports
assert (
'<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-realtime/2.2.0/leaflet-realtime.js"></script>' # noqa
in out
) # noqa

assert expected in out