Zoom to fit in ipyleaflet
I’ve been messing around with JupyterLab and the ipyleaflet widget for displaying mapping data.
I wanted to set up an interactive widget that allowed selection of a set of tracks from a list, but ipyleaflet doesn’t have a hook for Leaflet’s flyToBounds method, so I was having trouble making it focus the map on the right area.
Here’s a quick and dirty scheme for displaying a particular bounding rectangle in the map: make a map centered at the center of the bounds at the highest zoom level, then zoom out repeatedly until the bounds are within the frame of the map.
One slightly tricky thing is that the map doesn’t know its bounds until it’s drawn, so this has to be done reactively with a change observer.
Note that this probably does horrible things if the bounds cross the antimeridian (wrap around the world the wrong way). I’m not worrying about that because my points are guaranteed to fall between -180 and 180 degrees longitude.
Here’s a notebook using this technique.