Back to blog

    Finding Nearby Locations with PostGIS

    PostGISPostgreSQLBackend

    "Show me the nearest facilities within 5 km" sounds like a simple feature. In practice it's one of the places where a geospatial backend most often goes wrong: results are off by kilometers, or the query gets slower as the data grows.

    Here's the approach I usually use.

    Use geography when distance matters in meters

    If your data is stored as geometry in SRID 4326 (longitude/latitude), distance functions return values in degrees, not meters. One degree of longitude is about 111 km at the equator but much shorter near the poles, so a "radius" in degrees isn't a real radius.

    The simplest fix is to use the geography type, which calculates on the spheroid and returns meters:

    CREATE TABLE facilities (
      id    serial PRIMARY KEY,
      name  text NOT NULL,
      geog  geography(Point, 4326) NOT NULL
    );
    

    Don't forget the index

    Without a spatial index, every query scans the whole table. A GiST index fixes that:

    CREATE INDEX facilities_geog_idx ON facilities USING GIST (geog);
    

    Filter by radius with ST_DWithin

    A common mistake is filtering with ST_Distance(...) < 5000. That calculates the distance for every row and can't use the index. ST_DWithin can:

    SELECT id, name,
           ST_Distance(geog, ST_MakePoint($1, $2)::geography) AS distance_m
    FROM facilities
    WHERE ST_DWithin(geog, ST_MakePoint($1, $2)::geography, 5000)
    ORDER BY distance_m
    LIMIT 20;
    

    Note the argument order: ST_MakePoint(longitude, latitude). Swapping them is the most common bug I see, and it puts your user somewhere in the ocean.

    Need the nearest N, not "within X km"?

    When you just want the closest results with no fixed radius, use the KNN operator <-> in ORDER BY. It walks the index directly instead of computing every distance:

    SELECT id, name
    FROM facilities
    ORDER BY geog <-> ST_MakePoint($1, $2)::geography
    LIMIT 10;
    

    Summary

    • Use geography (or a projected CRS) so distances are in meters.
    • Always add a GiST index on the spatial column.
    • Filter with ST_DWithin, not ST_Distance < x.
    • Use <-> for "nearest N" queries.
    • Check the order: longitude first, then latitude.

    These four or five details are what separate a nearby-search feature that works in a demo from one that stays fast with millions of rows.