jupyter-widgets / ipyleaflet

A Jupyter - Leaflet.js bridge
https://ipyleaflet.readthedocs.io
MIT License
1.49k stars 364 forks source link

Callbacks for point_style? #911

Open deeplook opened 2 years ago

deeplook commented 2 years ago

A very late follow-up to https://github.com/jupyter-widgets/ipyleaflet/issues/362... would Leaflet allow to have a point_style_callback parameter for GeoJSON and GeoData layers like the style_callback one?

This would allow for styling such things like https://docs.mapbox.com/help/tutorials/show-changes-over-time/ more easily. See attached code and screenshot.

import requests
from geojson import FeatureCollection
from ipyleaflet import basemaps, GeoJSON, Map, WidgetControl
from ipywidgets import HTML, IntSlider

gj = requests.get("https://docs.mapbox.com/help/data/collisions1601.geojson").json()
feat_list = [
    GeoJSON(data=FeatureCollection(features=[
        feat for feat in gj["features"] if feat["properties"]["Hour"]==hour]
    ), point_style={"radius": 3})  # a dynamic style would be nice
    for hour in range(24)
]

m = Map(center=[40.7254, -73.8514], zoom=10, basemap=basemaps.CartoDB.Positron)
m += feat_list[0]

def slider_moved(event):
    if event["name"] == "value" and event["type"] == "change":
        old, new = event["old"], event["new"]
        m.remove_layer(feat_list[old])
        m.add_layer(feat_list[new])

title = "<h3>Bike Accidents in NYC, January 2016</h3>"
m += WidgetControl(widget=HTML(title), position="topright", transparent_bg=True)
slider = IntSlider(min=0, max=len(feat_list)-1, value=0, description="Hour")
slider.observe(slider_moved)
m += WidgetControl(widget=slider, position="bottomright", transparent_bg=True)

m

bike_accidents

deeplook commented 2 years ago

Ok, it's not only bikes, but motor vehicle collisions... ;)