Skip to content
Open
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
12 changes: 8 additions & 4 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -866,7 +866,7 @@ def render(self, **kwargs):
super().render()


TypeStyleMapping = dict[str, str | list[str | int]]
TypeStyleMapping = dict[str, str | list[str | int | float]]


class GeoJsonStyleMapper:
Expand Down Expand Up @@ -913,16 +913,20 @@ def _create_mapping(self, func: Callable, switch: str) -> TypeStyleMapping:
self._set_default_key(mapping)
return mapping

def get_feature_id(self, feature: dict) -> str | int:
"""Return a value identifying the feature."""
def get_feature_id(self, feature: dict) -> str | int | float:
"""Return a value identifying the feature.

A GeoJSON feature id can be a string or any number (RFC 7946), so
float ids are allowed as well.
"""
prefix = "feature.properties["
if self.feature_identifier.startswith(prefix):
key = json.loads(self.feature_identifier[len(prefix) : -1])
value = feature["properties"][key]
else:
fields = self.feature_identifier.split(".")[1:]
value = functools.reduce(operator.getitem, fields, feature)
assert isinstance(value, (str, int))
assert isinstance(value, (str, int, float))
return value

@staticmethod
Expand Down
32 changes: 32 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,38 @@ def test_geojson_empty_features_with_styling():
m.get_root().render()


def test_geojson_style_float_feature_ids():
"""Float feature ids are valid GeoJSON and can be used for styling."""
data = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": feature_id,
"properties": {},
"geometry": {"type": "Point", "coordinates": [0, 0]},
}
for feature_id in (1.5, 2.5, 3.5)
],
}
m = Map()
geojson = GeoJson(
data,
style_function=lambda f: {"color": "red" if f["id"] == 1.5 else "blue"},
highlight_function=lambda f: {"weight": 3},
).add_to(m)
assert geojson.feature_identifier == "feature.id"
rendered = m.get_root().render()
assert geojson.style_map == {
'{"color": "red"}': [1.5],
"default": '{"color": "blue"}',
}
assert geojson.highlight_map == {"default": '{"weight": 3}'}
assert "case 1.5:" in rendered
# The original ids are kept.
assert [f["id"] for f in geojson.data["features"]] == [1.5, 2.5, 3.5]


def test_geojson_event_handler():
"""Test that event handlers are properly generated"""
m = Map()
Expand Down
Loading