Skip to main content

13 - The Listing Map: Vector Tiles with PostGIS

How to serve the listing map: vector tiles with ST_AsMVT, grid aggregation by zoom and a byte-for-byte comparison with GeoJSON, on synthetic data.

What do you think about this article?

13 - The Listing Map: Vector Tiles with PostGIS
PropTechfedericocalo.dev

At a Glance

How to serve the listing map: vector tiles with ST_AsMVT, grid aggregation by zoom and a byte-for-byte comparison with GeoJSON, on synthetic data.

The map does not need an API that returns thousands of points

A map with a hundred thousand listings jams in one precise way: the interface calls an "all the listings in the window" endpoint, the server reads them, serializes them as GeoJSON and the browser downloads megabytes to draw dots that at that zoom level overlap. The alternative this article builds and measures is the vector tile (Mapbox Vector Tile, MVT): the database produces it ready-made with ST_AsMVT, for a square of the map identified by three numbers z/x/y, with integer coordinates and only the necessary properties. At low zoom the listings are aggregated into cells, because nobody can tell 70,000 points apart, and the number of elements per tile stays bounded.

The data is a hundred thousand made-up listings, in the rectangle around Lecce used in article 8, with a fixed seed. I ran the database (PostgreSQL 17.10 with PostGIS 3.5), the function that builds the tile, and a Node script that serves it, decodes it and compares it with GeoJSON. I did not run the MapLibre rendering, which needs a browser: the style that consumes the source is in the second-to-last section, declared "not run". The sizes in bytes are exact for this sample; the timings come from a 16-core machine and are not a benchmark.

From longitude and latitude to the z/x/y tile

A tiled map divides the world into a square of side 2z by 2z at each zoom level z; the tile x, y is identified by the column and the row, with the origin at the top left. The formula is the one from the OpenStreetMap page "Slippy map tilenames": longitude becomes x with a linear proportion, latitude y goes through the Web Mercator projection (the inverse hyperbolic sine of the tangent). But a hand-written formula that is off by one line shifts the map without raising errors, so the listing checks it against the PostGIS function that builds the same bounding box, ST_TileEnvelope.

From longitude and latitude to the z/x/y tile, checked against ST_TileEnvelope
import pg from 'pg';

// "Slippy map" tile (XYZ scheme, origin at the top left) that contains a point given in degrees.
export function tessera(lon, lat, z) {
  const n = 2 ** z;
  const x = Math.floor(((lon + 180) / 360) * n);
  const latRad = (lat * Math.PI) / 180;
  const y = Math.floor(((1 - Math.asinh(Math.tan(latRad)) / Math.PI) / 2) * n);
  return { z, x, y };
}

// Run only if the file is launched directly (not when another script imports it).
if (import.meta.url === `file://${process.argv[1]}`) {
  const db = new pg.Client();            // host, port and database come from the PGHOST, PGPORT, PGDATABASE variables
  await db.connect();
  const lecce = { lon: 18.1720, lat: 40.3515 };
  console.log('zoom  x      y      does the PostGIS tile contain the point?   side in metres');
  for (const z of [8, 12, 14, 16]) {
    const { x, y } = tessera(lecce.lon, lecce.lat, z);
    const { rows } = await db.query(
      `SELECT ST_Contains(ST_TileEnvelope($1, $2, $3), ST_Transform(ST_SetSRID(ST_MakePoint($4, $5), 4326), 3857)) AS inside,
              ST_XMax(ST_TileEnvelope($1, $2, $3)) - ST_XMin(ST_TileEnvelope($1, $2, $3)) AS side`,
      [z, x, y, lecce.lon, lecce.lat]);
    console.log(`${String(z).padStart(4)}  ${String(x).padEnd(5)}  ${String(y).padEnd(5)}  ${String(rows[0].inside).padEnd(41)} ${Math.round(rows[0].side)}`);
  }
  // The check that catches sign errors: the tile next to it must NOT contain the point.
  const { x, y } = tessera(lecce.lon, lecce.lat, 14);
  const accanto = await db.query(
    `SELECT ST_Contains(ST_TileEnvelope(14, $1, $2), ST_Transform(ST_SetSRID(ST_MakePoint($3, $4), 4326), 3857)) AS inside`,
    [x + 1, y, lecce.lon, lecce.lat]);
  console.log('tile to the right (x+1) contains the point:', accanto.rows[0].inside);
  await db.end();
}

// Output:
// zoom  x      y      does the PostGIS tile contain the point?   side in metres
//    8  140    96     true                                      156543
//   12  2254   1545   true                                      9784
//   14  9019   6181   true                                      2446
//   16  36076  24726  true                                      611
// tile to the right (x+1) contains the point: false

For every test zoom the computed tile contains the point (true), and the side of the tile halves at each level: 156,543 m at zoom 8, 9,784 at zoom 12, 2,446 at zoom 14, 611 at zoom 16. The last line is the check that catches sign errors: the neighbouring tile does not contain the point. If you hit the classic defect, the flipped y axis (with the tms scheme the row is counted from the bottom, as the MapLibre style specification says, with xyz from the top), the first check visibly turns false instead of showing a map shifted by a whole city.

The tile built by the database

The starting point is the listings table with a column of type geometry(Point, 3857), that is already in the reference system of the tiles. The choice goes against the habit of storing only the geography in degrees from article 8: a column in 3857 with its GiST index lets the filter use the index without transforming anything at every request (the proof is two sections further on). The price is that distances on this column are map distances, not real metres, and for those you keep the other column as well.

One hundred thousand synthetic listings in Web Mercator, with the GiST index
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS postgis;
DROP TABLE IF EXISTS annuncio;
CREATE TABLE annuncio (
  id        serial PRIMARY KEY,
  prezzo_mq integer NOT NULL,
  geom      geometry(Point, 3857) NOT NULL      -- Web Mercator: the SRID of the tiles
);

-- 100,000 SYNTHETIC listings in the same rectangle around Lecce as article 8, fixed seed.
SELECT setseed(0.42) AS seed \gset
INSERT INTO annuncio (prezzo_mq, geom)
SELECT 900 + floor(random() * 2200)::int,
       ST_Transform(ST_SetSRID(ST_MakePoint(18.0 + random() * 0.4, 40.2 + random() * 0.3), 4326), 3857)
FROM generate_series(1, 100000);
CREATE INDEX annuncio_geom_gist ON annuncio USING gist (geom);
ANALYZE annuncio;

SELECT count(*) AS listings, srid.srid, pg_size_pretty(pg_table_size('annuncio')) AS table_size,
       pg_size_pretty(pg_relation_size('annuncio_geom_gist')) AS index_size
FROM annuncio, (SELECT Find_SRID('public', 'annuncio', 'geom') AS srid) srid GROUP BY srid.srid;

-- Output:
--  listings | srid | table_size | index_size
-- ----------+------+------------+------------
--    100000 | 3857 | 6704 kB    | 4064 kB
-- (1 row)

The output confirms 100,000 rows with SRID 3857, 6,704 kB of table and 4,064 kB of index. Now the function. For each tile it builds two alternative sets, chosen by zoom. From zoom 14 up it returns the listings one by one, with ST_AsMVTGeom bringing each point into the 0-4096 coordinates of the tile. Below zoom 14 it groups them with ST_SnapToGrid: all the listings that fall in the same cell of a 64 × 64 grid become a single feature, with the count and the mean price. Finally ST_AsMVT packs everything into the annunci layer.

The tile as an SQL function: raw points from zoom 14, aggregated cells below
SET client_min_messages = warning;
-- The z/x/y tile as an SQL function: below zoom 14 it groups the listings into a 64 x 64 grid
-- (count and mean price per cell), from 14 up it returns the listings one by one.
CREATE OR REPLACE FUNCTION tessera(z int, x int, y int) RETURNS bytea
LANGUAGE sql STABLE PARALLEL SAFE AS $$
  WITH b AS (
    SELECT ST_TileEnvelope(z, x, y) AS g,
           (ST_XMax(ST_TileEnvelope(z, x, y)) - ST_XMin(ST_TileEnvelope(z, x, y))) AS lato
  ), grezzi AS (
    SELECT a.id, a.prezzo_mq, 1 AS annunci, ST_AsMVTGeom(a.geom, b.g, 4096, 64, true) AS geom
    FROM annuncio a, b
    WHERE z >= 14 AND a.geom && ST_Expand(b.g, b.lato * 64 / 4096)       -- the && operator uses the GiST index
  ), celle AS (
    SELECT NULL::int AS id, avg(a.prezzo_mq)::int AS prezzo_mq, count(*)::int AS annunci,
           ST_AsMVTGeom(ST_SnapToGrid(a.geom, b.lato / 64), b.g, 4096, 64, true) AS geom
    FROM annuncio a, b
    WHERE z < 14 AND a.geom && ST_Expand(b.g, b.lato * 64 / 4096)
    GROUP BY ST_SnapToGrid(a.geom, b.lato / 64), b.g
  )
  SELECT ST_AsMVT(t.*, 'annunci', 4096, 'geom')
  FROM (SELECT * FROM grezzi UNION ALL SELECT * FROM celle) t
  WHERE t.geom IS NOT NULL;
$$;

-- A quick check: length in bytes of the Lecce tile at zoom 14.
SELECT length(tessera(14, 9019, 6181)) AS bytes_zoom_14;

-- Output:
--  bytes_zoom_14
-- ---------------
--           9560
-- (1 row)

Three lines do the work. The filter a.geom && ST_Expand(b.g, ...) uses the index and takes the listings in the box plus a margin of 64 units out of 4096, the same value passed as buffer to ST_AsMVTGeom: the documentation proposes 256 as the default, I chose 64 to keep tiles small, and the margin is there so that a point just outside the box appears in the neighbouring tile and is not cut in half. The cell is lato / 64, with the side of the tile, and this aligns it to the tile edges: two adjacent tiles produce the same cells, with no smearing. The output says that the Lecce tile at zoom 14 weighs 9,560 bytes.

Serving the tile and looking inside the bytes

The Node listing has three parts. The handler(z, x, y) is the whole service: a parameterized query that returns the bytes, or an empty buffer if the tile has no features, which is not an error. Decoding with @mapbox/vector-tile and pbf shows that the bytes are a valid tile and lets you read what they contain. Then the same handler is put behind http.createServer, which serves a single request and shuts itself down: it is a proof that the header and the body match, not a service to leave running.

The z/x/y handler, decoding the tile, the comparison with GeoJSON and a server that serves a single request
import http from 'node:http';
import { gzipSync } from 'node:zlib';
import pg from 'pg';
import { PbfReader } from 'pbf';
import { VectorTile, VectorTileFeature } from '@mapbox/vector-tile';
import { tessera } from './02_tessera.mjs';

const db = new pg.Client();
await db.connect();

// The heart of the service: a function that takes z/x/y and returns the bytes of the tile.
async function handler(z, x, y) {
  const { rows } = await db.query('SELECT tessera($1, $2, $3) AS mvt', [z, x, y]);
  return rows[0].mvt ?? Buffer.alloc(0);          // a tile with no features is empty, not an error
}

// The same set of listings, as an API answering in GeoJSON would return it.
async function geojson(z, x, y) {
  const { rows } = await db.query(
    `SELECT json_build_object('type', 'FeatureCollection', 'features', coalesce(json_agg(json_build_object(
        'type', 'Feature', 'geometry', ST_AsGeoJSON(ST_Transform(geom, 4326))::json,
        'properties', json_build_object('id', id, 'prezzo_mq', prezzo_mq))), '[]'::json)) AS fc
     FROM annuncio WHERE geom && ST_TileEnvelope($1, $2, $3)`, [z, x, y]);
  return Buffer.from(JSON.stringify(rows[0].fc));
}

const lecce = { lon: 18.1720, lat: 40.3515 };
console.log('zoom  features  type      properties of the first         MVT bytes  MVT gzip   GeoJSON bytes (all points)');
for (const z of [8, 10, 12, 13, 14, 15]) {
  const { x, y } = tessera(lecce.lon, lecce.lat, z);
  const buf = await handler(z, x, y);
  const strato = new VectorTile(new PbfReader(buf)).layers.annunci;           // decoding: proof that the tile is valid
  const f = strato.feature(0);
  const gj = (await geojson(z, x, y)).length;      // all the points of the area, one by one
  console.log(`${String(z).padStart(4)}  ${String(strato.length).padStart(8)}  ${VectorTileFeature.types[f.type].padEnd(8)}  ${JSON.stringify(f.properties).padEnd(30)} ${String(buf.length).padStart(9)}  ${String(gzipSync(buf).length).padStart(9)}  ${gj}`);
}

// The coordinates inside the tile are integers 0..4096, not degrees.
const { x, y } = tessera(lecce.lon, lecce.lat, 14);
const primo = new VectorTile(new PbfReader(await handler(14, x, y))).layers.annunci.feature(0);
console.log('layer extent:', 4096, ' first point in tile coordinates:', JSON.stringify(primo.loadGeometry()[0][0]));

// The comparison that motivates the article: the same area as GeoJSON or as a tile, at zoom 14.
const mvt = await handler(14, x, y);
const gj = await geojson(14, x, y);
console.log(`zoom 14: GeoJSON ${gj.length} bytes (gzip ${gzipSync(gj).length}), tile ${mvt.length} bytes (gzip ${gzipSync(mvt).length})`);

// The same function behind HTTP: a server that serves ONE request and shuts itself down.
const server = http.createServer(async (req, res) => {
  const m = req.url.match(/^\/tiles\/(\d+)\/(\d+)\/(\d+)\.mvt$/);
  if (!m) { res.writeHead(404).end(); return; }
  const buf = await handler(...m.slice(1).map(Number));
  res.writeHead(200, { 'Content-Type': 'application/vnd.mapbox-vector-tile', 'Content-Length': buf.length });
  res.end(buf);
});
await new Promise((ok) => server.listen(0, '127.0.0.1', ok));
const risposta = await fetch(`http://127.0.0.1:${server.address().port}/tiles/14/${x}/${y}.mvt`);
const corpo = Buffer.from(await risposta.arrayBuffer());
console.log('HTTP', risposta.status, risposta.headers.get('content-type'), corpo.length, 'bytes, identical to the function:', corpo.equals(mvt));
await new Promise((ok) => server.close(ok));
await db.end();

// Output:
// zoom  features  type      properties of the first         MVT bytes  MVT gzip   GeoJSON bytes (all points)
//    8       285  Point     {"prezzo_mq":2052,"annunci":148}      6311       2608  9251505
//   10      3233  Point     {"prezzo_mq":2015,"annunci":17}     61260      21933  7604119
//   12      3025  Point     {"prezzo_mq":2569,"annunci":1}     62054      22154  624792
//   13      1089  Point     {"prezzo_mq":2291,"annunci":1}     23734       8594  152191
//   14       307  Point     {"id":110,"prezzo_mq":1995,"annunci":1}      9560       4907  38882
//   15        71  Point     {"id":326,"prezzo_mq":2758,"annunci":1}      2153       1260  8727
// layer extent: 4096  first point in tile coordinates: {"x":1895,"y":1281}
// zoom 14: GeoJSON 38882 bytes (gzip 5484), tile 9560 bytes (gzip 4907)
// HTTP 200 application/vnd.mapbox-vector-tile 9560 bytes, identical to the function: true

The table says what to keep at each zoom level. At zoom 8 the tile contains 70,289 listings, condenses them into 285 cells and weighs 6,311 bytes, against the 9,251,505 bytes of a GeoJSON with all the points. At zoom 10 and 12 the number of features rises to over 3,000 and the tile to about 61 kB, but it stays bounded by the grid (at most 64 × 64 = 4,096 cells) and does not grow with the number of listings, while the equivalent GeoJSON is 7.6 MB at zoom 10. From zoom 14 the tile keeps the real points: 307 features, 9,560 bytes, and each feature has the id to open the listing page. Be careful reading the numbers: the synthetic data is distributed uniformly, the worst case for aggregation, because density never concentrates; with real data concentrated in cities the countryside tiles will be lighter and the city-centre ones the same.

The comparison that gives the article its title is honest only if told with its caveats. For the same area at zoom 14 the GeoJSON weighs 38,882 bytes and the tile 9,560, about four times less; but with the gzip compression that almost every server applies, the two figures become 5,484 and 4,907 bytes, almost equal. Besides, the tile includes a 64-unit margin that the GeoJSON does not have. The advantage is not the byte saved at high zoom: it is that at low zoom the GeoJSON reaches megabytes and the tile does not, that the coordinates are already quantized and that the browser does not have to rebuild geometries. Remember too that the coordinates in the tile are integers from 0 to 4096 (the first point is at (1895, 1281)): turning them into degrees is the client's job, since it knows z/x/y.

Why the bounding-box filter decides everything

The listing that follows compares two ways of writing the same filter. The first compares the column with the box already in 3857, the second transforms the column to degrees before the comparison: it looks equivalent and gives the same result (307 rows), but the index is built on the column, not on the result of ST_Transform.

EXPLAIN of the bounding-box filter, with and without ST_Transform on the column
SET client_min_messages = warning;
-- The filter used inside tessera(), for the Lecce tile at zoom 14.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM annuncio
WHERE geom && ST_Expand(ST_TileEnvelope(14, 9019, 6181), 2446.0 * 64 / 4096);

-- The same filter written by transforming the column to degrees: the index is on the column, not on the function result.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM annuncio
WHERE ST_Transform(geom, 4326) && ST_Transform(ST_Expand(ST_TileEnvelope(14, 9019, 6181), 2446.0 * 64 / 4096), 4326);

-- Time of a whole tile (one run, warm cache, on this machine).
SELECT length(tessera(14, 9019, 6181)) AS warm_up;
\timing on
SELECT length(tessera(14, 9019, 6181)) AS bytes_zoom_14;
SELECT length(tessera(8, 140, 96)) AS bytes_zoom_8;

-- Output:
--                               QUERY PLAN
-- ------------------------------------------------------------
--  Aggregate (actual rows=1 loops=1)
--    ->  Bitmap Heap Scan on annuncio (actual rows=307 loops=1)
--          Recheck Cond: (geom && '0103000020…'::geometry)
--          Heap Blocks: exact=260
--          ->  Bitmap Index Scan on annuncio_geom_gist (actual rows=307 loops=1)
--                Index Cond: (geom && '0103000020…'::geometry)
-- (6 rows)
--
--                               QUERY PLAN
-- ------------------------------------------------------------
--  Aggregate (actual rows=1 loops=1)
--    ->  Seq Scan on annuncio (actual rows=307 loops=1)
--          Filter: (st_transform(geom, 4326) && '0103000020…'::geometry)
--          Rows Removed by Filter: 99693
-- (4 rows)
--
--  warm_up
-- ---------
--     9560
-- (1 row)
--
--  bytes_zoom_14
-- ---------------
--           9560
-- (1 row)
--
-- Time: 1.951 ms
--  bytes_zoom_8
-- --------------
--          6311
-- (1 row)
--
-- Time: 118.810 ms

The first plan is a Bitmap Index Scan on the GiST index that finds 307 rows reading 260 pages. The second is a Seq Scan: it reads the whole table and discards 99,693 rows, because no index describes ST_Transform(geom, 4326). With a hundred thousand rows the damage is contained, but the cost grows with the rows read (here it reads 100,000 for every tile) and a map needs dozens of tiles at a time. In the output I shortened the hexadecimal literal of the geometry and removed the excess dash lines: the rest is the real output. The timings are in the last lines of the listing: the zoom 14 tile is built in about 2 ms, the zoom 8 one, which aggregates 70,289 points, in about 119 ms. The second cost is paid on every request, and you get around it with a cache (HTTP or file level) or by precomputing the low levels.

One last place where you get hurt concerns the parameters. The handler's regular expression accepts only digits, but does not limit the values: tessera(40, 0, 0) answers «ST_TileEnvelope: Invalid tile zoom value, 40» and tessera(3, 9, 0) «Invalid tile x value, 9». A database error that comes out as a 500 on a public address must be intercepted beforehand: validate that z is between 0 and 15 (here maxzoom) and that x and y are less than 2z, and answer 404.

The client side: the style, not run

To draw the tile you need a client such as MapLibre GL JS, which requires a browser and which I did not run. The style below is written against the MapLibre style specification (the tiles, minzoom, maxzoom properties of a vector source and source-layer, circle-radius, circle-color of a layer) and is a schema to adapt, not a result. Its point is to show the link with the server.

The MapLibre style that consumes the source (a schema to adapt, not run)
{
  "version": 8,
  "sources": {
    "annunci": {
      "type": "vector",
      "tiles": ["http://localhost:3000/tiles/{z}/{x}/{y}.mvt"],
      "minzoom": 0,
      "maxzoom": 15
    }
  },
  "layers": [
    {
      "id": "celle",
      "type": "circle",
      "source": "annunci",
      "source-layer": "annunci",
      "maxzoom": 14,
      "paint": {
        "circle-radius": ["interpolate", ["linear"], ["get", "annunci"], 1, 3, 150, 14],
        "circle-color": ["interpolate", ["linear"], ["get", "prezzo_mq"], 900, "#9ecae1", 3100, "#08519c"],
        "circle-opacity": 0.7
      }
    },
    {
      "id": "punti",
      "type": "circle",
      "source": "annunci",
      "source-layer": "annunci",
      "minzoom": 14,
      "paint": { "circle-radius": 4, "circle-color": "#08519c" }
    }
  ]
}

The source-layer must be equal to the layer name given to ST_AsMVT, here annunci: if it does not match, the map stays empty and no error signals it. Two layers split the work with maxzoom: 14 and minzoom: 14, in line with the point where the SQL function switches branch; the radius of the circles follows the count for the cells and the colour follows the mean price. The URL in the source points to a local example service: the served tile must have Content-Type: application/vnd.mapbox-vector-tile, the type that the format specification recommends and that the listing verified in the response.

Where this fits in the series

Article 8 explains the GiST index and the SRID that are taken here as known; article 1 explains why a list of listings is paginated, while a map is not. The H3 cells of article 12 are an alternative to the grid aggregation used here, when you need a zone that stays stable from one tile to the next. For text search on the same listings see article 11.

Previous in the series: 12. H3 Geographic Indexing for the Real Estate Market. Next in the series: 14. Building Sensor Time Series in PostgreSQL.

What you can do now

You can compute the tile of a point and check it against PostGIS, build a tile with ST_AsMVTGeom and ST_AsMVT using the index, and decide for each zoom whether to send real points or aggregated cells. You can measure the difference against GeoJSON and state it with its caveats (compression reduces it a lot), you know why a column already in 3857 avoids a full scan, and you know which parameters to validate before exposing the handler. What stays out, and I say so, is the behaviour in a real browser.

Sources

Five listings were run on 2026-11-12 with PostgreSQL 17.10, PostGIS 3.5, Node 24.11 and the pg, pbf and @mapbox/vector-tile packages, with the comments and labels in English (the output shown is the one from that run). The listings are synthetic, with a fixed seed. The MapLibre style was not run (it requires a browser). The execution plan outputs have the hexadecimal literal of the geometry shortened.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects