Using rio-tiler in Lonboard¶
This notebook shows how to use rio-tiler as a dynamic tile source for a Lonboard RasterLayer.
Instead of pre-generating tiles, Lonboard calls a user-provided fetch_tile(x, y, z) coroutine whenever the map needs a tile. We implement that function with the rasterio-based rio_tiler.io.Reader, run in a worker thread with asyncio.to_thread so it doesn't block the event loop.
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "lonboard>=0.17.0",
# "rio-tiler",
# ]
# ///
import asyncio
# Tile Matrix Set definitions (WebMercatorQuad, ...)
import morecantile
from morecantile.models import TMSBoundingBox
# rio-tiler: rasterio-based reader and output data model
from rio_tiler.io import Reader
from rio_tiler.models import ImageData
# Lonboard: map widget, raster tile layer and helpers
from lonboard import Map, RasterLayer
from lonboard._geoarrow.ops import Bbox
from lonboard.raster import EncodedImage
Open the COG¶
We use a Sentinel-2 True Color Image (TCI) Cloud Optimized GeoTIFF hosted on S3.
We open it once to grab the metadata Lonboard needs to set up the layer: geographic bounds, zoom range and center.
# Full URL to the COG (GDAL handles HTTP access via /vsicurl/)
src_path = "https://titiler-benchmark-public.s3.us-east-1.amazonaws.com/cogs/S2C_33TVF_20260928_0_L2A_TCI.tif"
with Reader(input=src_path) as src:
# Dataset bounds in WGS84 (west, south, east, north)
bounds = src.get_geographic_bounds(crs="EPSG:4326")
# Zoom levels (in WebMercatorQuad) matching the dataset's overviews/resolution
minzoom = src.minzoom
maxzoom = src.maxzoom
# Initial map center
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2)
Tile rendering¶
Lonboard separates fetching tile data from rendering it. The render function receives whatever fetch_tile returned (here a rio-tiler ImageData) and must return an encoded image.
The TCI file is already 8-bit RGB, so no rescaling or colormap is needed: ImageData.render encodes the data (plus the mask as alpha channel) to PNG.
def render_rgb_tile(img: ImageData) -> EncodedImage:
"""Convert the image data to an RGBA PNG."""
# `render` returns PNG bytes; the mask is written as the alpha band
return EncodedImage(data=img.render(img_format="PNG"), media_type="image/png")
Fetch tiles¶
fetch_tile is a coroutine called by Lonboard for each visible tile. The rio_tiler.io.Reader (GDAL/rasterio) methods are synchronous, so we run them in a worker thread with asyncio.to_thread to avoid blocking the event loop (and the map) while tiles are being read.
We also build a WebMercatorQuad TileMatrixSet whose boundingBox is restricted to the dataset extent, so Lonboard only requests tiles that intersect the image.
async def fetch_tile(
x: int,
y: int,
z: int,
) -> ImageData:
"""Read a WebMercatorQuad tile with the rasterio Reader in a worker thread."""
def get_tile(x, y, z):
# Blocking (GDAL) read
with Reader(input=src_path) as src:
return src.tile(x, y, z)
# Offload the blocking call so the event loop stays responsive
img = await asyncio.to_thread(get_tile, x, y, z)
return img
# Restrict the WebMercatorQuad TMS to the dataset extent so Lonboard
# doesn't request tiles outside the image
west, south, east, north = bounds
web_mercator = morecantile.tms.get("WebMercatorQuad")
tms = web_mercator.model_copy(
update={
"boundingBox": TMSBoundingBox(
lowerLeft=web_mercator.xy(west, south),
upperRight=web_mercator.xy(east, north),
crs=web_mercator.crs,
),
},
)
layer = RasterLayer(
_tile_matrix_set=tms, # tiling grid used to compute (x, y, z)
_crs="EPSG:3857", # CRS of the returned tiles
_fetch_tile=fetch_tile, # async function returning tile data
_render_tile=render_rgb_tile, # function encoding tile data to an image
min_zoom=0,
max_zoom=maxzoom, # don't request tiles finer than the native resolution
extent=bounds,
_bounds=Bbox(*bounds),
_center=center,
)
# Create the map
m = Map(layer, height=800)
m