🚀 Jumpstart 2027: Custom, Secure AI Workflows to Adopt Now. Reserve your spot →

Chris Parmer

Chris Parmer

November 5, 2026

Vector Tile Maps in 20 Minutes, a Beginner's Guide for Data People

TL;DR

  • A vector tile is one square of a map at one level of detail. The map downloads only the squares on screen, so a layer of 712,768 US river lines that took 103 s to draw as a 452 MB GeoJSON file drew in 4.4 s as 6 tiles and 170 KB.
  • Tiles are built from an ordinary table with a geometry column. A CSV of latitude and longitude, a shapefile, a GeoPackage, a GeoPandas frame or a PostGIS table all work, and DuckDB turns any of them into tiles with one SQL query per tile.
  • Zoomed out, a tile should carry only what a pixel can show: big rivers instead of every creek, simplified lines, larger basins instead of tiny watersheds and one point per pixel. In our examples those rules made zoomed-out tiles 17 to 25 times smaller.
  • Every step below has a picture, a short piece of code and a prompt you can paste into a coding agent such as Claude Code, and the steps add up to a Dash app in one file of about 170 lines.

This post builds up, step by step, to the map below: every river in the lower 48 and 8,082 live stream gauges, served from a DuckDB file by a Python app and drawn in a Plotly map, smooth from the whole country down to a street in Dallas:

A Dash app titled US rivers and stream gauges, as vector tiles, zooming with the mouse wheel from the whole lower 48 into Dallas, Texas: zoomed out only the big rivers show and gauges are thinned, then smaller streams appear, the stream order slider hides small streams and brings them back, and the map ends at street level on the Trinity River in downtown Dallas, with a counter of 142 tiles and 2,339 KB served

And this is the problem it solves. The same layer of river lines, drawn in the same Plotly map, as one GeoJSON file and as vector tiles:

Two maps of the lower 48. Left, one GeoJSON file of all 712,768 NHDPlus river reaches: 452 MB (121 MB gzipped), 103 s until drawn, a blue haze of every line. Right, vector tiles: 6 tiles and 170 KB, 4.4 s until drawn, showing only the rivers of stream order 7 and up (43,520 reaches) at this zoom, with the rest arriving as you zoom in. An empty map with only the basemap took 3.4 s.

Most data people meet this problem the same way. You have a big layer in a file or a database (every well, every parcel, every census tract, every stream), you send it to a web map as GeoJSON, and it works until the layer reaches tens of thousands of shapes. GIS teams on ArcGIS never hit it, because an ArcGIS map service or vector tile service quietly does what this post explains: it cuts the layer into small squares and sends only the ones on screen. The format underneath, the Mapbox Vector Tile specification, is open, and you can produce it from Python with a database you already have.

Every example uses the same public US data, so the numbers can be compared: 712,768 river reaches of stream order 3 and up from NHDPlus V2.1 (the national stream network from the US EPA and USGS; stream order counts how many tributaries join, so order 3 is a small stream and order 10 is the lower Mississippi), 8,082 USGS stream gauges with today's flow, and 87,028 small watersheds (HUC12, the smallest drainage areas in the USGS Watershed Boundary Dataset). Times are from a 4-vCPU cloud machine with DuckDB 2.0, Plotly 7.1 and Dash 4.5.

1. What do vector tiles do for you?

A map in a browser can only show so much at once: about 1,600 by 1,000 pixels. GeoJSON sends everything anyway, every line at full detail, whether it's on screen or a pixel wide. Here's what that cost for the rivers, against tiles:

What the browser loaded

Size

Time until drawn

GeoJSON, 43,520 reaches (stream order 7+)

17.8 MB

7.6 s

GeoJSON, 206,708 reaches (stream order 5+)

104 MB

22.5 s

GeoJSON, all 712,768 reaches

452 MB (121 MB gzipped)

103 s

Vector tiles, lower 48

6 tiles, 170 KB

4.4 s

Vector tiles, Dallas at zoom 7

9 tiles, 103 KB

4.3 s

Vector tiles, Dallas at zoom 11

9 tiles, 6.7 KB

3.8 s

About 3.4 s of every row is the page and basemap: an empty map took that long. With tiles, the data costs about the same at every zoom, because the browser always asks for about a screen's worth of squares, and each square only holds what's visible at that zoom.

Prompt: Write a Python script that times a large line layer in a Plotly map two ways in headless Chromium with Playwright: as one GeoJSON file loaded by URL into a layout.map.style geojson source, and as vector tiles from a local tile route. Wait until MapLibre reports map.loaded() and map.areTilesLoaded(), and print the bytes downloaded and seconds for each.

2. What's inside a vector tile?

A tile is one square patch of the map at one zoom level, holding only the features that touch that patch, simplified to that zoom's level of detail. So the same place carries different things at different scales. Here is what the tile covering Dallas held at three zooms, decoded from the tiles our server sent:

Three decoded tiles that cover Dallas. Zoom 4, one tile about 2,106 km across (tile 4/3/6): 12,034 river lines, 1,048 gauges and 803 watershed basins, 58,218 vertices, 167 KB gzipped, showing only big rivers across Texas and its neighbors. Zoom 7, about 263 km across (tile 7/29/51): 785 river lines, 101 gauges, 765 watersheds, 18,728 vertices, 54 KB. Zoom 11, about 16 km across (tile 11/473/826): 5 river lines, 4 gauges, 7 watersheds, 1,055 vertices, 3 KB, with the Trinity River at full detail

Tile over Dallas

Covers about

River lines

Gauges

Watersheds

Vertices

Gzipped

4/3/6

2,106 km

12,034 (order 7+, simplified)

1,048 (thinned)

803 merged basins

58,218

167 KB

7/29/51

263 km

785 (order 5+)

101

765

18,728

54 KB

11/473/826

16 km

5 (all, full detail)

4 (all)

7

1,055

3 KB

That's the whole idea. Zoomed out, a tile carries only the big rivers, with their lines simplified, watersheds merged into larger basins and one gauge per few pixels. Zoomed in, it carries every stream and gauge at full detail, but only for a few square kilometers. You decide what goes into each zoom, and section 3 shows how.

Prompt: Fetch the vector tile 11/473/826 for my "rivers" layer from http://127.0.0.1:8060/tiles/rivers/11/473/826.pbf, gunzip it if needed, decode it with the mapbox-vector-tile package, and print the number of features, the total vertices and the properties of the first feature.

This will create code like this:

import gzip, urllib.request
import mapbox_vector_tile
raw = urllib.request.urlopen("http://127.0.0.1:8060/tiles/rivers/11/473/826.pbf").read()
tile = mapbox_vector_tile.decode(gzip.decompress(raw))
features = tile["rivers"]["features"]
print(len(features), "features", features[0]["properties"])

3. How do you get your data into vector tiles?

A vector tile isn't made from a special map file. It's made from a table: one row per feature, a geometry column, and the columns you want to color by or click on. Get your data into a DuckDB (or PostGIS) table like that and one SQL query can cut it into tiles. Here's the whole path, from a file on your laptop to a tile you can check.

Check what you have

Before loading anything, find out the geometry type, the row count and the coordinate system (CRS, which says what the numbers in the coordinates mean). The Census county shapefile, for example, is 3,222 polygons in NAD83 (EPSG:4269), and the gauges CSV has no geometry at all, only lat and lon columns.

Prompt: For my file cb_2023_us_county_20m.zip (a zipped shapefile), print the row count, the geometry types and the coordinate system with GeoPandas, and for gauges.csv print the column names and types with DuckDB's DESCRIBE.

This will create code like this:

import duckdb, geopandas as gpd
gdf = gpd.read_file("cb_2023_us_county_20m.zip")
print(len(gdf), gdf.geom_type.unique(), gdf.crs) # 3222 ['Polygon' 'MultiPolygon'] EPSG:4269
print(duckdb.sql("DESCRIBE SELECT * FROM read_csv('gauges.csv')"))

Load it into a table with a geometry column

Each kind of source needs one line. A CSV of points gets its geometry from two columns with ST_Point(lon, lat), a shapefile, GeoPackage, GeoJSON or file geodatabase comes in through ST_Read, and a GeoPandas frame goes through a GeoParquet file. If your data is already in PostGIS, it already has a geometry column.

Prompt: With DuckDB's spatial extension, create a gauges table from gauges.csv with a point geometry from its lon and lat columns, a counties table from the zipped shapefile cb_2023_us_county_20m.zip with ST_Read, and a table from a GeoDataFrame saved with to_parquet and read back with read_parquet.

This will create code like this:

con = duckdb.connect("tiles.duckdb")
con.load_extension("spatial")
con.execute("SET geometry_always_xy = true") # x is longitude, y is latitude
con.execute("CREATE TABLE gauges AS SELECT name, condition, ST_Point(lon, lat) AS geom FROM read_csv('gauges.csv')")
con.execute("""CREATE TABLE counties AS SELECT GEOID, NAME, geom
FROM ST_Read('/vsizip/cb_2023_us_county_20m.zip/cb_2023_us_county_20m.shp')""")
gdf.to_parquet("counties.parquet") # from GeoPandas
con.execute("CREATE TABLE counties_gp AS SELECT GEOID, NAME, geometry AS geom FROM read_parquet('counties.parquet')")

In PostGIS the CSV case is ST_SetSRID(ST_MakePoint(lon, lat), 4326) after a \copy into a plain table.

Transform once to Web Mercator

Tiles are squares in Web Mercator (EPSG:3857), the projection every web map uses, so each tile query compares your geometry with a square in Web Mercator meters. Transforming on every request is slow, because the database transforms every row before it can compare: a zoomed-in river tile over Dallas took 1,034 ms that way. Transforming once when you load the data, and indexing the result, took the same tile to 2.2 ms.

Order matters here. ST_Point takes x then y, which is longitude then latitude, the opposite of how people say coordinates. Swap them and DuckDB doesn't raise an error:

A chart of longitude against latitude with the valid range of the Earth shaded. ST_Point(lon, lat) puts the 8,082 USGS gauges in the shape of the US. ST_Point(lat, lon) puts the 3,883 gauges east of 90°W near the South Pole and gives the other 4,199 a latitude below -90, off the Earth, which DuckDB turns into POINT (inf inf) without an error, so they vanish from the map

Prompt: In DuckDB, create my gauges and counties tables with their geometry transformed to EPSG:3857 as they load: the gauges CSV has EPSG:4326 longitude and latitude columns, and the counties shapefile is EPSG:4269. Then check a few gauges with ST_AsText to make sure no point came out as inf.

This will create code like this:

con.execute("""CREATE OR REPLACE TABLE gauges AS
SELECT name, condition, flow_cfs, ST_Transform(ST_Point(lon, lat), 'EPSG:4326', 'EPSG:3857') AS geom
FROM read_csv('gauges.csv')""")
con.execute("""CREATE OR REPLACE TABLE counties AS
SELECT GEOID, NAME, ST_Transform(geom, 'EPSG:4269', 'EPSG:3857') AS geom
FROM ST_Read('/vsizip/cb_2023_us_county_20m.zip/cb_2023_us_county_20m.shp')""")
print(con.sql("SELECT name, ST_AsText(geom) FROM gauges LIMIT 3"))

Transform while you create the table, and avoid doing it later with an UPDATE: DuckDB 2.0 keeps the coordinate system in the column's type, and in our test an UPDATE left the old EPSG:4269 label on the new coordinates.

Keep only the columns you'll use

Every column you select goes into every feature of every tile. The county shapefile has 13 columns besides its geometry. Sent with all of them, the zoom 4 tile over Texas held 935 counties in 150.6 KB (85 KB gzipped). With only GEOID and NAME, the same tile was 60.8 KB (40 KB gzipped). Select the columns the map colors by or shows on click, and look up the rest in SQL when someone clicks.

Prompt: Change my counties tile query to select only GEOID and NAME as properties, and compare the tile size in bytes, raw and gzipped, against selecting every column.

Add a spatial index

A zoomed-in tile needs the few features in one small square, and without an index the database tests every row to find them. For the zoom 11 tile over downtown Dallas, DuckDB tested all 712,768 river reaches and took 156 ms. An R-tree index (a spatial index that stores each shape's bounding box in a tree) finds the 5 reaches whose boxes touch the tile first, and the same tile took 2.7 ms:

River reaches near downtown Dallas, each with its gray bounding box, the zoom 11 tile 11/473/826 outlined in purple, and the 5 boxes the R-tree index returns in orange, out of 712,768. Without the index the tile query took 156 ms; with it, 2.7 ms

Prompt: Add an R-tree index on the geom column of my DuckDB rivers, gauges and counties tables, then run EXPLAIN on my tile query and confirm the plan shows an Rtree Index Scan.

This will create code like this:

for table in ["rivers", "gauges", "counties"]:
con.execute(f"CREATE INDEX {table}_geom ON {table} USING RTREE (geom)")

One trap: wrapping the clipped rows in an outer WHERE geom IS NOT NULL makes DuckDB skip the index, and the same tile took 916 ms. Leave that filter out, since ST_AsMVT drops empty geometries on its own. In PostGIS the index is USING GIST (geom).

Decide what each zoom shows

This is where section 2's tiles come from. Zoomed out, a tile that carries every reach at full detail is mostly invisible bytes: the zoom 4 tile over Texas held 174,770 reaches, 2,038 KB gzipped, and took 541 ms to build. A small table of rules, one row per zoom range, fixes it:

Zooms

Rivers shown

Lines simplified to

0 to 4

Stream order 7 and up (43,520 reaches)

9,800 m, about one pixel at zoom 4

5 to 7

Stream order 5 and up (206,708)

1,200 m

8 to 10

Stream order 4 and up (389,625)

150 m

11 and in

All 712,768

Full detail

Two decoded copies of the zoom 4 tile over Texas. Left, every reach at full detail: 174,770 features, 2,038 KB gzipped, 541 ms to build, a dense mesh of streams. Right, the zoom 0-4 rule, stream order 7 and up simplified to about a pixel: 12,034 features, 81 KB gzipped, 50 ms, showing the main rivers

With the rule, the same tile was 12,034 reaches, 81 KB gzipped and 50 ms: 25 times smaller and 11 times faster, and on screen it shows the rivers you'd actually see at that zoom.

Prompt: Build four DuckDB tables from my rivers table for four zoom ranges: zooms 0-4 with stream_order >= 7 simplified with ST_Simplify(geom, 9800), zooms 5-7 with stream_order >= 5 simplified to 1200, zooms 8-10 with stream_order >= 4 simplified to 150, and zoom 11 and up using the full table. Index each one, and make the tile function pick the table for the requested zoom.

This will create code like this:

RULES = [((0, 4), "rivers_z0", "stream_order >= 7", 9_800),
((5, 7), "rivers_z5", "stream_order >= 5", 1_200),
((8, 10), "rivers_z8", "stream_order >= 4", 150)]
for _, table, where, tolerance in RULES:
con.execute(f"""CREATE TABLE {table} AS SELECT name, stream_order, ST_Simplify(geom, {tolerance}) AS geom
FROM rivers WHERE {where}""")
con.execute(f"CREATE INDEX {table}_geom ON {table} USING RTREE (geom)")
def table_for(z):
return next((t for (lo, hi), t, _, _ in RULES if lo <= z <= hi), "rivers")

Check that it worked

Fetch one tile straight from the database, decode it, and count what's inside before you build any map. The zoom 9 tile over Dallas, 9/118/206, held 22 gauges in 1,324 bytes (726 gzipped), the first one the West Fork Trinity River at Grand Prairie.

Prompt: Build the vector tile 9/118/206 from my DuckDB gauges table with ST_TileEnvelope, ST_AsMVTGeom and ST_AsMVT, decode it with mapbox-vector-tile, and print the feature count, the byte size raw and gzipped, and the first feature's properties and tile coordinates.

This will create code like this:

TILE = """SELECT ST_AsMVT(t, '{layer}', 4096, 'geom') FROM (
SELECT {cols}, ST_AsMVTGeom(geom, ST_Extent(ST_TileEnvelope($z, $x, $y)), 4096, 64, true) AS geom
FROM {table} WHERE ST_Intersects(geom, ST_TileEnvelope($z, $x, $y))) t"""
sql = TILE.format(layer="gauges", cols="name, condition", table="gauges")
body = bytes(con.execute(sql, {"z": 9, "x": 118, "y": 206}).fetchone()[0])
features = mapbox_vector_tile.decode(body)["gauges"]["features"]
print(len(features), "gauges,", len(body), "bytes,", features[0]["properties"])

That query is the only tile code you need. ST_TileEnvelope gives the tile's square, ST_AsMVTGeom clips each geometry to it and converts it to the tile's grid, and ST_AsMVT packs the rows into a tile. The same three functions exist in PostGIS.

4. What does a tile look like on the inside?

GeoJSON stores every coordinate as a long decimal number in text. A tile stores each point as a pair of whole numbers on a 4,096 by 4,096 grid inside the tile, packed in a binary format (protobuf), which is a large part of why tiles are small:

An illustrative square in downtown Dallas encoded into tile 11/473/826 and decoded again. Its corners sit at whole-number coordinates (826, 1460), (1526, 1460), (1526, 2153) and (826, 2153) on the tile's 0 to 4096 grid, where (0, 0) is -96.855, 32.843 and (4096, 4096) is -96.680, 32.695. The tile is 66 bytes and the same square as GeoJSON is 247 bytes

At zoom 11 one grid unit is about 4 m, which is finer than a screen pixel at that zoom, and each zoom in halves it.

Prompt: Make an illustrative square polygon in downtown Dallas in WGS84, transform it to EPSG:3857 in DuckDB, encode it into tile 11/473/826 with ST_AsMVTGeom and ST_AsMVT, decode it with mapbox-vector-tile, and print the corner coordinates on the 4096 grid and the tile's size against the same square as GeoJSON.

5. Why do tiles overlap their neighbors a little?

A shape that crosses a tile edge is cut in two, one piece per tile. Cut exactly at the edge, each piece gets a new closing line along that edge, and an outlined shape shows a seam where the tiles meet. The 64 in ST_AsMVTGeom(..., 4096, 64, true) is a buffer: each piece runs 64 grid units past the edge, where the map hides it under the next tile:

An illustrative 2.5 km circle in Dallas that straddles the edge between tiles 11/473/826 and 11/474/826, outlined. With buffer 0 each tile's piece is closed along the tile edge and the outline shows a vertical seam through the circle. With buffer 64 each piece runs past the edge and the circle draws without a seam

Prompt: Show why vector tiles use a buffer: buffer a point on the edge between tiles 11/473/826 and 11/474/826 into a 2.5 km circle in DuckDB, clip it into both tiles with ST_AsMVTGeom at buffer 0 and at buffer 64, and plot both tiles side by side with Plotly, drawing only the part of each piece inside its own tile.

6. How does the map know which tiles to ask for?

Every tile has an address: its zoom, then its column and row in that zoom's grid. At zoom 0 one tile covers the world, and each zoom splits every tile into four, so zoom 9 has 512 by 512 tiles. The map works out which addresses cover the screen and requests them from a URL template like /tiles/rivers/{z}/{x}/{y}.pbf. Here are the requests the browser made for one view of Dallas, drawn over that view:

A map of the Dallas area at zoom 9 with 12 tiles outlined in purple and labeled with their addresses, 9/116/205 through 9/119/207, and the gzipped size of each tile's gauges and rivers, between 0.2 and 2.1 KB. To draw the view the map asked for 12 tiles in 24 requests, 21.8 KB in total

That's 12 tiles, 24 requests (one per layer per tile) and 21.8 KB for this view. The server side is one Flask route. With Dash, it goes on the Flask server inside your app:

Prompt: Add a Flask route /tiles/<layer>/<z>/<x>/<y>.pbf to my Dash app's server that builds a vector tile from my DuckDB tables with ST_AsMVT, picks the river table for the zoom, uses one DuckDB cursor per thread, gzips the tile, caches it with functools.lru_cache, and returns it with Content-Type application/vnd.mapbox-vector-tile and Content-Encoding gzip.

This will create code like this:

import functools, gzip, threading
import flask
from dash import Dash
app = Dash(__name__)
local = threading.local()
@functools.lru_cache(maxsize=4096)
def tile(layer, z, x, y):
if not hasattr(local, "cur"):
local.cur = con.cursor() # one cursor per server thread
if layer == "rivers":
sql = TILE.format(layer="rivers", cols="name, stream_order", table=table_for(z))
else:
sql = TILE.format(layer="gauges", cols="name, condition, flow_cfs", table="gauges")
body = local.cur.execute(sql, {"z": z, "x": x, "y": y}).fetchone()[0]
return gzip.compress(bytes(body)) if body else b""
@app.server.route("/tiles/<layer>/<int:z>/<int:x>/<int:y>.pbf")
def tiles(layer, z, x, y):
if layer not in ("rivers", "gauges"):
flask.abort(404)
body = tile(layer, z, x, y)
headers = {"Content-Type": "application/vnd.mapbox-vector-tile", "Cache-Control": "public, max-age=3600"}
if body:
headers["Content-Encoding"] = "gzip"
return flask.Response(body, headers=headers)

7. How do you draw vector tiles in a Plotly map?

Plotly's map traces are built on MapLibre, and layout.map.style accepts a full MapLibre style: a list of sources (your tile URL) and layers that say how to draw them. Layers can color and size features by their properties with MapLibre expressions, such as step for stream order and match for the gauge's flow condition:

The finished Dash app at the lower 48: rivers drawn darker and wider by stream order, gauges colored by today's flow from much below normal (red) to much above normal (dark blue), with a stream order slider, layer checkboxes, a legend and a counter of tiles served

Prompt: Draw my tile routes in a Plotly go.Scattermap figure by putting a full MapLibre style in layout.map.style: an Esri World Light Gray raster basemap, a vector source for /tiles/rivers/{z}/{x}/{y}.pbf and one for gauges with absolute URLs and maxzoom 14, a line layer colored with a step expression on stream_order and widened with an interpolate expression, and a circle layer colored with a match expression on condition. Set uirevision so the view survives updates.

This will create code like this:

import plotly.graph_objects as go
order = ["coalesce", ["get", "stream_order"], 3]
src = lambda name: {"type": "vector", "tiles": [f"{origin}/tiles/{name}/{{z}}/{{x}}/{{y}}.pbf"], "maxzoom": 14}
style = {"version": 8,
"sources": {"basemap": {"type": "raster", "tileSize": 256, "tiles": [ESRI_LIGHT_GRAY]},
"rivers": src("rivers"), "gauges": src("gauges")},
"layers": [{"id": "basemap", "type": "raster", "source": "basemap"},
{"id": "rivers", "type": "line", "source": "rivers", "source-layer": "rivers",
"paint": {"line-color": ["step", order, "#8ab8e0", 5, "#3d7fc1", 7, "#174f8c"],
"line-width": ["interpolate", ["linear"], order, 3, 0.4, 6, 1.0, 10, 3.2]}},
{"id": "gauges", "type": "circle", "source": "gauges", "source-layer": "gauges",
"paint": {"circle-color": ["match", ["get", "condition"], "Much below normal", "#b2182b",
"Below normal", "#ef8a62", "Normal", "#1baf7a", "Above normal", "#67a9cf",
"Much above normal", "#2a4fb0", "#b9b6ae"]}}]}
fig = go.Figure(go.Scattermap())
fig.update_layout(map=dict(style=style, center=dict(lat=38.5, lon=-96), zoom=3.6), uirevision="keep")

The tile URLs have to be absolute (http://host/tiles/...), so build origin from flask.request.host_url in the callback that returns the figure. To restyle the tiles already loaded, for example hiding streams below the slider's order, change the MapLibre layer in the browser with a clientside callback (map.setFilter('rivers', ...)). Sending a new style from Python makes Plotly redraw the whole map, and while testing we saw the view jump back to an earlier position when the style changed right after a zoom.

Prompt: Add a Dash clientside callback that takes my stream order slider and layer checklist, finds the MapLibre map at document.querySelector('#map .js-plotly-plot')._fullLayout.map._subplot.map, and calls map.setFilter on the rivers layer and map.setLayoutProperty('visibility') on the rivers and gauges layers, without sending a new figure.

8. How do you keep zoomed-out tiles small?

Section 3's per-zoom rules handled the rivers. Two more kinds of data need their own rule when zoomed out.

Small polygons: swap in a coarser layer

At zoom 4 a pixel is about 9.8 km, and most HUC12 watersheds are smaller than 2 by 2 pixels. Sending all of them made the zoom 4 tile over Texas 27,250 watersheds, 1,192 KB gzipped and 2,173 ms to build. Dropping the ones under 2 by 2 pixels left 70 features and an almost empty map. Swapping in the same watersheds merged into 2,425 larger basins (by their 8-digit HUC8 code and outlet) kept the picture at 803 features, 58 KB and 132 ms:

Three decoded copies of the zoom 4 tile over Texas. Every small HUC12 watershed: 27,250 features, 1,192 KB gzipped, 2,173 ms, a dense mesh. Only watersheds bigger than 2 x 2 pixels: 70 features, 10 KB, 89 ms, an almost empty tile. A coarser layer of HUC8 basins: 803 features, 58 KB, 132 ms, a readable map of basins

Prompt: My DuckDB watersheds table has a huc8 column and a drains_to column. Make a watershed_overview table by grouping on huc8 and drains_to with ST_Union_Agg, simplify it, index it, and serve it instead of watersheds for tiles below zoom 6.

Points: one per pixel, or counts

A pixel can only show one dot. A 1 million point sample of US places from Overture Maps put 214,707 points in the zoom 4 tile over Texas: 1,167 KB gzipped and 421 ms. Keeping one point per pixel cut it to 11,993 points, 70 KB and 263 ms, and counting points per 8 by 8 pixel cell instead cut it to 648 features and 5 KB:

Two decoded copies of the zoom 4 tile over Texas from a 1 million point sample of Overture Maps places. Every point: 214,707 features, 1,167 KB gzipped, 421 ms. One point per pixel: 11,993 features, 70 KB, 263 ms. On screen the tile is 256 pixels across, so a pixel can only show one dot

Prompt: For zoomed-out tiles of my DuckDB places table, keep one point per pixel: compute the pixel size as 156543 / 2**z meters, and use QUALIFY row_number() OVER (PARTITION BY floor(ST_X(geom) / cell), floor(ST_Y(geom) / cell)) = 1 inside the tile query, only below zoom 8.

This will create code like this:

cell = 156_543 / 2 ** z # one pixel at zoom z, in meters
thinned = f"""(SELECT * FROM places WHERE ST_Intersects(geom, ST_TileEnvelope($z, $x, $y))
QUALIFY row_number() OVER (PARTITION BY floor(ST_X(geom) / {cell}), floor(ST_Y(geom) / {cell})) = 1)"""

9. Why cache and gzip tiles?

People pan back and forth, and every tile they revisit would otherwise be rebuilt. Building the zoom 4 river tile took 52.7 ms the first time and 0.003 ms from functools.lru_cache, and a Cache-Control header lets the browser skip the request altogether. Tiles also compress well: that tile went from 241 KB to 81 KB with gzip. Both are already in the route in section 6.

Prompt: Measure what caching and gzip do for my tile route: time one tile request cold and again from functools.lru_cache, and print the tile's size before and after gzip.compress.

10. When should you pre-generate tiles instead?

Building tiles from SQL when the browser asks keeps them current and lets you filter them per request. If your data changes rarely and nobody filters it, you can instead build every tile once with a tool like tippecanoe and save them in one PMTiles file, which a CDN or object storage can serve with no database running. Both produce the same tile format, so the Plotly map doesn't change.

Prompt: Export my rivers table from DuckDB to GeoJSONSeq, build a PMTiles file with tippecanoe for zooms 0 to 12 that drops small features when zoomed out, and point the rivers source in my MapLibre style at it with the pmtiles:// protocol.

11. Putting it all together

The app at the top of this post is one Python file of about 170 lines: load the CSV and the GeoParquet into DuckDB, transform once, apply the per-zoom rules, index, serve tiles from a Flask route, and draw them in a Plotly map with a clientside restyle. From the whole lower 48 down to a street in Dallas, it served 142 tiles and 2,339 KB.

Prompt: Build a single-file Dash app that serves vector tiles from DuckDB. At startup, load data/gauges.csv (name, condition, flow_cfs, lat, lon) with ST_Point(lon, lat) and data/rivers.parquet (GeoParquet with name, stream_order, geometry in EPSG:4326), transform both to EPSG:3857, make river tables for zooms 0-4 (stream_order >= 7, ST_Simplify 9800), 5-7 (>= 5, 1200) and 8-10 (>= 4, 150), and add R-tree indexes. Serve /tiles/<layer>/<z>/<x>/<y>.pbf with ST_AsMVT, one gauge per 4 x 4 pixel cell below zoom 8, gzip and lru_cache. Draw both layers in a Plotly map with a full MapLibre style (rivers colored by stream order, gauges by condition), add a stream order slider and layer checkboxes that restyle the map with a clientside callback, and show a count of tiles served.

Where to go next

  • How to serve vector tiles from Python goes deeper: the same queries in PostGIS, clicks on tile features, 3D columns, DuckDB 2.0's slowdowns and a larger watershed app with full benchmarks.
  • Maps at scale in Dash compares tiles with Plotly traces, deck.gl and dash-leaflet on the same 566,902 points, so you can pick the right one for your layer size.
  • The Python maps guide covers every other kind of map you can make in Python.

Summary

Vector tiles let a browser draw layers of hundreds of thousands of features by downloading only the squares on screen, each holding only what's visible at its zoom. You make them from an ordinary table: load your CSV, shapefile or GeoDataFrame into DuckDB with a geometry column, transform it once to Web Mercator, keep the columns you need, index it, and write down what each zoom should show. One SQL query per tile and one Flask route do the rest, and a Plotly map with a MapLibre style draws them.

FAQ

bluesly
x
instagram
youtube
medium
fcaebook

Product

© 2026
Plotly. All rights reserved.
Cookie Preferences
aicpa/soc2