localtileserver

Turn a local GeoTIFF or COG into pan/zoom-able slippy-map tiles, served from your own Shiny process – no tile service, no upload, and it works deployed.

localtileserver puts raster data – elevation, imagery, a scientific grid – on a map, with band selection, colormaps, and value rescaling, and without converting it to vector tiles. It builds an ordinary ipyleaflet tile layer, so it works with @render_ipyleaflet or @render_leafmap like any other layer.

hero

A 1999 aerial survey of Exuma, Bahamas, rendered from a sample raster bundled with the package. Try the app.

Installation

pip install 'shinywidgets[ipyleaflet]' 'localtileserver>=1.0.0'

localtileserver 1.0 or later is required for tiles to work in a deployed app.

Quick start

A TileClient wraps a raster; get_leaflet_tile_layer() turns it into a layer you add to an ordinary ipyleaflet.Map. This example uses localtileserver.examples.get_bahamas(), a 1999 aerial RGB survey of Exuma shipped inside the package itself, so it needs no network and no sample data of your own:

# Bundled real RGB imagery (no network needed): a 1999 aerial survey of
# Exuma, Bahamas, shipped inside the localtileserver package itself.
import ipyleaflet as L
from localtileserver import TileClient, examples, get_leaflet_tile_layer
from shiny.express import ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="localtileserver quickstart", fillable=True)

# Create the TileClient at module scope, never inside a render: the first
# open takes a few seconds, later layers on the same server are fast.
client: TileClient = examples.get_bahamas()

with ui.card():

    @render_ipyleaflet
    def map():
        m = L.Map(center=client.center(), zoom=9)
        m.add(get_leaflet_tile_layer(client))
        return m

quickstart

For your own data, TileClient("path/to/raster.tif") and TileClient("https://.../raster.tif") work the same way – the latter streams over GDAL’s /vsicurl/, so only the tiles your users actually view are fetched. Create the client once at module scope, as above; inside a render function it would re-open the file on every re-render. localtileserver.examples ships several more sample rasters (get_san_francisco(), get_co_elevation(), get_elevation(), get_landsat(), get_oam2(), among others) if you want to try the examples below with real data before pointing at your own.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Reacting to interaction

localtileserver has no accessors of its own. Reactivity comes from ipyleaflet’s accessors on the renderer, combined with TileClient methods that turn a click or a drawn shape into a question about the raster.

Click to sample a point

clicked() gives you a coordinate; client.point(lon, lat) samples the raster there directly, server-side – not the (possibly colormapped and rescaled) pixel the browser happens to be showing. This example samples a USGS 1m elevation DEM over a slice of the Colorado Rockies:

# Public COG over the network: a USGS 1m DEM of a slice of the Colorado
# Rockies, served from a public bucket via /vsicurl/.
import ipyleaflet as L
from localtileserver import TileClient, examples, get_leaflet_tile_layer
from shiny.express import render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Click to sample the raster", fillable=True)

client: TileClient = examples.get_co_elevation()
STATS = client.statistics()["b1"]

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card():

        @render_ipyleaflet
        def map():
            m = L.Map(center=client.center(), zoom=14)
            m.add(get_leaflet_tile_layer(client, colormap="terrain", vmin=STATS["min"], vmax=STATS["max"]))
            return m

    with ui.card():
        ui.card_header("Elevation at your last click")

        @render.ui
        def elevation():
            c = map.clicked()
            if c is None:
                return "Click the map to sample the DEM there."
            lat, lng = c["coordinates"]
            # Sampled server-side, straight from the source raster -- not from
            # the (possibly rescaled/colormapped) tile the browser is showing
            value = client.point(lng, lat).array[0]
            return ui.div(
                ui.h5(f"{value:.0f} m"),
                f"at {lat:.4f}, {lng:.4f}",
            )

client.point() returns a PointData; .array is the per-band value at that coordinate – index [0] for a single-band DEM, or keep the whole array for an RGB raster.

ipyleaflet’s bounds() is useful here too, for recomputing client.statistics() or a summary chart over only the visible extent.

Updating in place

Style lives in the tile URL, so restyling a layer is just reassigning its url. This example drives band, colormap, and a vmin/vmax range from sidebar inputs, over a public NAIP aerial COG of San Francisco Bay served via /vsicurl/:

# Public COG over the network: NAIP aerial imagery of San Francisco Bay,
# served from a public bucket via /vsicurl/ (first open takes a few seconds).
import ipyleaflet as L
from localtileserver import TileClient, examples, get_leaflet_tile_layer
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Restyle in place", fillable=True)

client: TileClient = examples.get_san_francisco()
BANDS = {"Red (b1)": [1], "Green (b2)": [2], "Blue (b3)": [3], "True color": [1, 2, 3]}
COLORMAPS = ["greys", "viridis", "magma", "terrain"]

render_count = reactive.value(0)

with ui.sidebar():
    ui.input_select("band", "Band", list(BANDS), selected="True color")
    ui.input_select("colormap", "Colormap (single band only)", COLORMAPS)
    ui.input_slider("range", "Value range (vmin/vmax)", 0, 255, value=[0, 255])

    @render.code
    def renders():
        return f"map() has rendered {render_count()} time(s)"

with ui.card():

    @render_ipyleaflet
    def map():
        with reactive.isolate():
            render_count.set(render_count() + 1)
        m = L.Map(center=client.center(), zoom=13)
        m.add(get_leaflet_tile_layer(client, indexes=[1, 2, 3]))
        return m


@reactive.effect
def _restyle():
    indexes = BANDS[input.band()]
    kwargs = {} if len(indexes) > 1 else {"colormap": input.colormap()}
    url = client.get_tile_url(
        indexes=indexes,
        vmin=input.range()[0],
        vmax=input.range()[1],
        client=True,
        **kwargs,
    )
    map.widget.layers[1].url = url

The sidebar counts calls to map(): changing the band, colormap, or range leaves it at 1, so the map keeps its pan and zoom while the tiles change. Pass client=True to get_tile_url(); the default returns a URL only the server can reach.

Colormap names are rio-tiler colormaps, lowercase ("terrain", "magma"), and apply to a single band only. An invalid name raises inside the effect and ends the session, so validate user-facing choices against rio_tiler.colormap.cmap.list().

Re-render instead when the number or structure of layers changes. See Updating in place for the general pattern.

Linking widgets

drawn_features() returns GeoJSON; client.feature(geometry, indexes=..., encoding="npy") crops the raster to that geometry and returns a raw NumPy array – the last band is always a 0/255 validity mask marking which pixels actually fall inside the (possibly non-rectangular) shape, so mask it out before computing statistics. Here, drawing a shape on the map recomputes a histogram in a second, separate widget:

# Bundled real RGB imagery (no network needed): a 1999 aerial survey of
# Exuma, Bahamas, shipped inside the localtileserver package itself.
import io

import ipyleaflet as L
import numpy as np
import plotly.express as px
from localtileserver import TileClient, examples, get_leaflet_tile_layer
from shiny.express import render, ui
from shinywidgets import render_ipyleaflet, render_plotly

ui.page_opts(title="Draw a region, compute zonal stats", fillable=True)

client: TileClient = examples.get_bahamas()

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card():

        @render_ipyleaflet
        def map():
            m = L.Map(center=client.center(), zoom=11)
            m.add(get_leaflet_tile_layer(client))
            m.add(L.DrawControl(rectangle={"shapeOptions": {}}, polygon={}, circle={}, polyline={}, marker={}))
            return m

    with ui.card(full_screen=True):
        ui.card_header("Band 1 (red) histogram inside the drawn shape")

        @render_plotly
        def hist():
            feats = map.drawn_features()  # [] until something is drawn
            if not feats:
                return px.histogram()
            # client.feature() takes GeoJSON straight from drawn_features() --
            # no CRS conversion needed, unlike client.part()'s bbox (see Gotchas)
            raw = client.feature(feats[-1]["geometry"], indexes=[1], encoding="npy")
            band, mask = np.load(io.BytesIO(raw))
            values = band[mask > 0]  # drop pixels outside the (non-rectangular) shape
            return px.histogram(values, nbins=40, labels={"value": "pixel value (band 1)"})

hist re-renders on purpose: each new shape holds a different number of pixels. Polygons and circles work too; client.feature() crops to the shape itself, not its bounding box.

Large data

Raster data never leaves the server: only the tiles the current view needs are read and sent, however large the source, and a remote COG is never downloaded in full. The limit is how fast each tile is generated, which COG overviews keep bounded even for country-scale rasters. See the Large data & performance article for the other two approaches, used by widgets that render discrete points or polygons rather than a continuous raster.

Deployment

An app that shows localtileserver layers works when deployed, to Posit Connect, shinyapps.io, or any other server, including under a sub-path, with no extra setup. That includes URLs your own code builds with client.get_tile_url(). Requests through the app reach only the rasters your app has rendered; requests for any other file or URL are refused. The tile server’s own port has no such guard, so keep it private (it listens only on 127.0.0.1 by default). Set SHINYWIDGETS_LOOPBACK_PROXY_DISABLE=1 to opt out.

Gotchas

  • client.part(bbox) reads the bbox in the raster’s own CRS unless you pass bounds_crs="EPSG:4326", even though client.bounds() and client.center() return lon/lat. Without it, a lon/lat bbox silently returns a tiny, meaningless crop. client.feature() takes GeoJSON, which is always lon/lat, which is why the drawing example uses it.

Learn more