Skip to content
Speaking of GIS

Architecture guide

How to Ship Drive-Time & Service-Area Maps Without Google Maps API Fees

An end-to-end open stack for drive-time and service-area maps: MapLibre GL JS, PMTiles, Valhalla and US Census ZCTAs, with code that compiles and the costs we could verify.

Last tested
Level
Intermediate
Versions
maplibre-gl 6.19.0 · pmtiles 4.5.0 · @protomaps/basemaps 5.7.2 · Valhalla 3.9.3 (public FOSSGIS instance) · PostGIS 3 (SQL only)

A drive-time map answers one question: from this point, where can you get in N minutes by road? Commercial map APIs sell that answer per request, bundled with a basemap you also pay for per load. Every piece has a mature open-source equivalent, and the pieces fit together with less code than most people expect.

This guide builds the whole stack:

  • Basemap: one PMTiles file on static storage, rendered by MapLibre GL JS. No tile server.
  • Drive-time polygons: your own Valhalla instance, behind a small API that validates requests.
  • “Which ZIP areas are inside?”: US Census ZCTA polygons in PostGIS, intersected with the isochrone.

The browser code below compiles under TypeScript strict mode against maplibre-gl 6.19.0, pmtiles 4.5.0 and @protomaps/basemaps 5.7.2. The Valhalla request is the one we sent to the public FOSSGIS server on 24 November 2026; the map underneath is its actual response.

Drive time (road network)≤ 5 min≤ 10 min≤ 15 min05 km© OpenStreetMap contributors · Valhalla
Valhalla drive-time areas of 5, 10 and 15 minutes from downtown Austin, Texas. The shapes stretch along highways and are far from circular. Requested from the public FOSSGIS Valhalla server on 24 November 2026.

The architecture

Two things happen on a schedule and three at request time. The schedule builds data: a basemap archive and a routing graph, both from the same OpenStreetMap extract, plus a one-off load of Census boundaries. At request time the browser reads basemap bytes straight from storage, and asks your API for an isochrone, which your API gets from Valhalla and optionally joins to ZCTAs.

BUILD (weekly or monthly)REQUEST TIMEOSM extractGeofabrik .osm.pbfBasemap tilespmtiles extract / PlanetilerRouting graphValhalla tile buildCensus ZCTAsTIGER/Line → PostGISBrowserMapLibre GL JSObject storage.pmtiles + glyphs + spritesYour API/api/isochrone (validates)ValhallaPOST /isochronePostGISZCTAs ∩ isochroneRange

The split matters for cost and for reliability. The basemap is static files, so it scales like a CDN. Valhalla is the only process doing real work, and it only runs when someone asks for a polygon, not on every pan and zoom.

Step 1: a basemap from one PMTiles file

PMTiles packs a whole tile pyramid into one file with an index at the front. MapLibre asks for pmtiles://… URLs, the pmtiles library turns each tile into an HTTP range request, and any static host that supports Range serves it. The PMTiles on R2 guide covers extracting your region, uploading and CORS. Here is the browser side.

map.ts
import { Map as MapLibreMap, addProtocol, type GeoJSONSource } from "maplibre-gl"
import { Protocol } from "pmtiles"
import { layers, namedFlavor } from "@protomaps/basemaps"

const protocol = new Protocol()
addProtocol("pmtiles", protocol.tile)

const map = new MapLibreMap({
  container: "map",
  center: [-97.7431, 30.2672],
  zoom: 10,
  style: {
    version: 8,
    glyphs: "https://protomaps.github.io/basemaps-assets/fonts/{fontstack}/{range}.pbf",
    sprite: "https://protomaps.github.io/basemaps-assets/sprites/v4/light",
    sources: {
      protomaps: {
        type: "vector",
        url: "pmtiles://https://maps.example.com/austin.pmtiles",
        attribution: '<a href="https://protomaps.com">Protomaps</a> © <a href="https://openstreetmap.org/copyright">OpenStreetMap</a>',
      },
    },
    layers: layers("protomaps", namedFlavor("light"), { lang: "en" }),
  },
})

Fonts and sprites are separate files. The URLs above point at the Protomaps assets on GitHub Pages, which is fine for a prototype; copy them to your own bucket before you launch so the map does not depend on someone else’s hosting.

Step 2: isochrones from your own Valhalla

Valhalla computes isochrones natively: one location, up to four contours by default, each a time (minutes) or distance (kilometres). The public server at valhalla1.openstreetmap.de is run by FOSSGIS volunteers, and their terms rule out using it as a substantial part of a commercial product or from high-traffic websites. Use it to try a request; build on your own instance.

The scripted Docker image downloads an extract and builds routing tiles on first start:

shell
docker run -dt --name valhalla -p 8002:8002 \
  -v "$PWD/custom_files:/custom_files" \
  -e tile_urls=https://download.geofabrik.de/north-america/us/texas-latest.osm.pbf \
  ghcr.io/valhalla/valhalla-scripted:latest

curl -s localhost:8002/status   # {"version":"3.9.x", ...} once tiles are built

Do not let the browser talk to Valhalla directly. Put a thin API in front that validates input against the service limits, sets a timeout and hides the internal URL. The limits below mirror Valhalla’s defaults (max_contours: 4, max_time_contour: 120); if you raise them in valhalla.json, raise them here too.

isochrone.ts (server)
const VALHALLA = process.env.VALHALLA_URL ?? "http://localhost:8002"

export async function isochrone(lon: number, lat: number, minutes: number[]) {
  if (minutes.length > 4 || minutes.some((m) => !(m > 0 && m <= 120))) throw new Error("1-4 contours, each 1-120 minutes")
  const res = await fetch(`${VALHALLA}/isochrone`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      locations: [{ lat, lon }],
      costing: "auto",
      contours: minutes.map((time) => ({ time })),
      polygons: true,
      denoise: 0.5,
      generalize: 50,
    }),
    signal: AbortSignal.timeout(10_000),
  })
  if (!res.ok) throw new Error(`Valhalla ${res.status}: ${await res.text()}`)
  return res.json()
}

polygons: true returns fills instead of lines. denoise: 0.5 drops islands smaller than half the main area (the default of 1 keeps only the largest ring). generalize: 50 simplifies outlines with a 50 m Douglas-Peucker tolerance, which kept our 15-minute polygon at 1,559 vertices and the whole three-contour response at 53 KB. The isochrone guide explains what each of these does to the shape.

Step 3: draw the polygons

Valhalla returns the contours largest first (our response came back 15, 10, 5 minutes), so drawing features in order puts the small, important area on top. Color by the contour property it sets on each feature:

map.ts (continued)
type Isochrone = GeoJSON.FeatureCollection<GeoJSON.Polygon | GeoJSON.MultiPolygon, { contour: number }>

async function drawIsochrone(lon: number, lat: number) {
  const res = await fetch("/api/isochrone", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ lon, lat, minutes: [5, 10, 15] }),
  })
  const data: Isochrone = await res.json()
  const source = map.getSource("isochrone") as GeoJSONSource | undefined
  if (source) return source.setData(data)
  map.addSource("isochrone", { type: "geojson", data })
  map.addLayer({
    id: "isochrone-fill",
    type: "fill",
    source: "isochrone",
    paint: {
      "fill-color": ["match", ["get", "contour"], 5, "#b84a27", 10, "#e8a25c", "#0f6b6e"],
      "fill-opacity": 0.45,
    },
  })
}

map.on("click", (e) => drawIsochrone(e.lngLat.lng, e.lngLat.lat))

Step 4: which ZIP areas fall inside

Sales and service teams think in ZIP codes, but ZIP codes are mail routes, not shapes. The Census Bureau’s ZIP Code Tabulation Areas (ZCTAs) are the usable polygon stand-in; the ZCTA guide covers the differences in detail. Load the cartographic boundary file once:

shell
curl -O https://www2.census.gov/geo/tiger/GENZ2020/shp/cb_2020_us_zcta520_500k.zip
ogr2ogr -f PostgreSQL PG:"dbname=gis" /vsizip/cb_2020_us_zcta520_500k.zip \
  -nln zcta -nlt PROMOTE_TO_MULTI -lco GEOMETRY_NAME=geom -t_srs EPSG:4326
psql gis -c "CREATE INDEX ON zcta USING gist (geom);"

Then intersect with the isochrone GeoJSON and report how much of each ZCTA is covered, measured on the spheroid:

zctas_in_isochrone.sql
WITH iso AS (
  SELECT ST_SetSRID(ST_GeomFromGeoJSON($1), 4326) AS geom   -- one feature's geometry
)
SELECT z.zcta5ce20 AS zcta,
       round((ST_Area(ST_Intersection(z.geom, iso.geom)::geography)
            / ST_Area(z.geom::geography))::numeric, 3) AS share_inside
FROM zcta z, iso
WHERE ST_Intersects(z.geom, iso.geom)
ORDER BY share_inside DESC;

Decide up front what “inside” means. A ZCTA that is 4% covered usually should not be on the list; a threshold such as 0.5, or a population-weighted share using block-level counts, is easier to defend than “touches the polygon”.

What it costs

“No API fees” is not “free”. What disappears is the per-request charge; what remains is storage, bandwidth, compute and your time. Numbers we could verify on 24 November 2026:

  • Basemap storage. Our Austin-area extract is 56.9 MB; the full planet build from 20 November 2026 is 139.7 GB. Cloudflare R2 lists $0.015 per GB-month with the first 10 GB free and no egress fee, so the planet costs about $1.95 a month to store and a city costs nothing.
  • Basemap reads. Every uncached tile is a range read, which R2 bills as a Class B operation: $0.36 per million after 10 million free a month. A CDN cache in front cuts this further.
  • Valhalla. One always-on server sized to your region. A metro area runs on a small VM; a continent needs far more memory to build tiles. We have not measured build times for large regions, so check the Valhalla docs for current requirements.
  • Your time. Rebuilding the extract and routing graph on a schedule, upgrades, monitoring. This is the real cost, and the reason small projects sometimes should stay on a hosted API.

Google prices its Maps Platform per SKU and has changed the model more than once, so compare against its current pricing page for your own call volumes rather than any figure quoted in an article, including ours.

Limits you inherit

  • No live traffic. Without a traffic feed, Valhalla uses typical speeds from road class and tags. A 15-minute area at 5:30 p.m. is smaller than the map says.
  • Data freshness is your job. New roads appear when you rebuild both the basemap and the routing graph.
  • No search. Typing an address needs a geocoder (Nominatim, Photon or Pelias, self-hosted for production use).
  • Attribution. Show “© OpenStreetMap contributors” on the map and wherever you export the polygons.

When this is the wrong choice

  • You make a few hundred isochrone requests a month: a hosted API’s free tier is cheaper than any server.
  • Rush-hour accuracy matters more than cost: you need a provider with live and historical traffic.
  • Nobody on the team can own a server and a monthly data rebuild.
  • You need a few maps, not a product. IsochroneMaps draws drive-time areas and ZIP territories in the browser without any of this setup (it is built by the same team as Speaking of GIS).

Found an error or a step that no longer works? Write to info@adeptaoperations.com; we correct guides and note the change date. More in the guide index.