Skip to main content

08 - Geospatial Search & Location Services with PostGIS

How to search properties by radius, proximity and neighbourhood with PostGIS: geometry or geography, GiST index, ST_DWithin, ST_Covers and swapped coordinates.

What do you think about this article?

08 - Geospatial Search & Location Services with PostGIS
PropTechPhoto:Danny MenesesPexels

At a Glance

How to search properties by radius, proximity and neighbourhood with PostGIS: geometry or geography, GiST index, ST_DWithin, ST_Covers and swapped coordinates.

"Homes within 500 metres" is a question the database can answer, if you ask it properly

On a property portal, search by location is the function users use more than any other: "homes near the sea", "inside this neighbourhood", "the closest to this office". It can be solved by computing the distance between the searched point and every listing, but with a hundred thousand listings that is a way of making every search pay for a full scan. PostgreSQL with the PostGIS extension can answer far more cheaply, provided you know three points where it is easy to go wrong: which data type to use, how to write the query so that the index gets used, and in which order the coordinates go.

The three listings are SQL run on PostgreSQL 17.10 with PostGIS 3.5. The points are 100,000 random positions in a rectangle around Lecce, generated with a fixed seed: they are not real properties, and the rows and metres I report describe that sample.

Geometry or geography: the choice that decides the units

PostGIS has two types for points on the Earth. The geometry type treats coordinates as on a flat sheet: the distance between two points is expressed in the unit of the reference system, which for GPS coordinates (SRID 4326) is degrees. The geography type treats coordinates as longitude and latitude on an ellipsoid, and returns distances in metres. The PostGIS documentation warns that with geography fewer functions are defined and those that are cost more CPU: the choice depends on the application's working area.

Distance between Lecce and Brindisi with geometry, with geography, and with the coordinates swapped
SET client_min_messages = warning;
-- Lecce (lon 18.1720, lat 40.3515) and Brindisi (lon 17.9367, lat 40.6327).
-- WATCH the order: PostGIS wants (longitude, latitude), that is (x, y).
WITH p AS (
  SELECT ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326) AS lecce,
         ST_SetSRID(ST_MakePoint(17.9367, 40.6327), 4326) AS brindisi
)
SELECT round(ST_Distance(lecce, brindisi)::numeric, 4)                    AS geometry_gradi,
       round((ST_Distance(lecce::geography, brindisi::geography) / 1000)::numeric, 1) AS geography_km,
       round(ST_Distance(ST_SetSRID(ST_MakePoint(40.3515, 18.1720), 4326)::geography,
                         ST_SetSRID(ST_MakePoint(40.6327, 17.9367), 4326)::geography)::numeric / 1000) AS ordine_invertito_km
FROM p;

-- Output:
--  geometry_gradi | geography_km | ordine_invertito_km
-- ----------------+--------------+---------------------
--          0.3667 |         37.1 |                  40
-- (1 row)

The run shows all three things. With geometry the distance is 0.3667: a number that cannot be expressed in metres, because it is degrees, and a degree of longitude is not worth a degree of latitude. With geography it is 37.1 km, a directly usable value. The third column is the most insidious defect: I swapped the two arguments of ST_MakePoint, which wants (longitude, latitude), that is (x, y), whereas many systems say "lat, lon". The result is 40 km: a plausible number, wrong by three kilometres and with no error at all. Always put a range check on the input (latitude lies between -90 and 90) and, when you write the data, a test with a known location whose distance you know.

For a portal at regional or national scale, geography with SRID 4326 is the safe choice: the units are metres and you do not have to handle projections. For a heavy calculation on a small area, such as a single municipality, geometry in a local flat projection may be better: the functions are faster but you must know which projection you are using. The compromise is speed against simplicity and there is no absolutely right answer.

Proximity: the index is used only if the query is written to use it

The listing creates the table with 100,000 points and counts those within 500 metres of the centre of Lecce, first without an index and then with a GiST index (Generalized Search Tree), the structure PostGIS uses for spatial data. Then it asks for the three closest. Instead of time, which varies from machine to machine, I look at how many rows the database reads.

Radius search with and without a GiST index, and the three closest points with the <-> operator
SET client_min_messages = warning;
DROP TABLE IF EXISTS immobile;
CREATE TABLE immobile (id serial PRIMARY KEY, posizione geography(Point, 4326) NOT NULL);

-- 100,000 points scattered in a rectangle around Lecce (invented data, fixed seed).
SELECT setseed(0.42) AS seme \gset
INSERT INTO immobile (posizione)
SELECT ST_SetSRID(ST_MakePoint(18.0 + random() * 0.4, 40.2 + random() * 0.3), 4326)::geography
FROM generate_series(1, 100000);
ANALYZE immobile;

-- 500-metre radius from the centre of Lecce, WITHOUT a spatial index.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM immobile
WHERE ST_DWithin(posizione, ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326)::geography, 500);

CREATE INDEX immobile_gist ON immobile USING gist (posizione);
ANALYZE immobile;

-- Same query, WITH a GiST index: look at how many rows the scan node reads.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM immobile
WHERE ST_DWithin(posizione, ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326)::geography, 500);

-- The 3 closest: ORDER BY with the <-> operator uses the index (KNN). Distance in metres.
SELECT id, round((posizione <-> ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326)::geography)::numeric) AS metri
FROM immobile
ORDER BY posizione <-> ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326)::geography
LIMIT 3;

-- Output:
--                                                               QUERY PLAN
-- ---------------------------------------------------------------------------------------------------------------------------------------
--  Aggregate (actual rows=1 loops=1)
--    ->  Seq Scan on immobile (actual rows=64 loops=1)
--          Filter: st_dwithin(posizione, '0101000020E610000079E92631082C3240A245B6F3FD2C4440'::geography, '500'::double precision, true)
--          Rows Removed by Filter: 99936
-- (4 rows)
--
--                                                                   QUERY PLAN
-- -----------------------------------------------------------------------------------------------------------------------------------------------
--  Aggregate (actual rows=1 loops=1)
--    ->  Bitmap Heap Scan on immobile (actual rows=64 loops=1)
--          Filter: st_dwithin(posizione, '0101000020E610000079E92631082C3240A245B6F3FD2C4440'::geography, '500'::double precision, true)
--          Rows Removed by Filter: 45
--          Heap Blocks: exact=105
--          ->  Bitmap Index Scan on immobile_gist (actual rows=109 loops=1)
--                Index Cond: (posizione && _st_expand('0101000020E610000079E92631082C3240A245B6F3FD2C4440'::geography, '500'::double precision))
-- (7 rows)
--
--   id   | metri
-- -------+-------
--  59585 |    56
--  63841 |    56
--  37217 |    73
-- (3 rows)

Without the index the plan is a Seq Scan: it reads all the rows, discards 99,936 and keeps 64. With the index the plan becomes a Bitmap Index Scan that finds 109 candidates with a fast comparison on the bounding boxes (the && operator against the point expanded by 500 metres), and then the exact st_dwithin filter discards 45 and keeps the same 64. The result is identical, the reading goes from a hundred thousand rows to a little over a hundred. ST_DWithin is the right function because the documentation specifies that it includes a bounding-box comparison that uses the available indexes. Writing ST_Distance(a, b) < 500 instead forces the database to compute the distance of every row, and the index is of no use.

The last query answers "the three closest" with ORDER BY posizione <-> punto LIMIT 3. The <-> operator is designed for this use: the documentation says that, used in ORDER BY, it gives index-assisted proximity results. In my sample the three closest points are at 56, 56 and 73 metres from the centre. For geography the documentation specifies that the neighbour search is based on a sphere and not on the ellipsoid, so distances may differ slightly from those of ST_Distance: for ordering the results it is fine, to show an exact distance to the user recompute it with ST_Distance.

Polygons: the neighbourhood is an area, and the edge is a case to decide

The "inside this neighbourhood" search uses a polygon. The listing draws a neighbourhood as a rectangle of about 850 metres by 780 and tests four points: one inside, one on the edge, one a few metres outside and one with latitude and longitude swapped.

Points inside, on the edge and outside a polygon with ST_Covers
SET client_min_messages = warning;
-- A neighbourhood drawn by hand: a rectangle of about 0.85 km x 0.78 km.
WITH quartiere AS (
  SELECT ST_GeogFromText('SRID=4326;POLYGON((18.17 40.35, 18.18 40.35, 18.18 40.357, 18.17 40.357, 18.17 40.35))') AS g
), punti(nome, g) AS (
  VALUES ('dentro',          ST_GeogFromText('SRID=4326;POINT(18.175 40.353)')),
         ('sul bordo',       ST_GeogFromText('SRID=4326;POINT(18.17 40.353)')),
         ('fuori di poco',   ST_GeogFromText('SRID=4326;POINT(18.1695 40.353)')),
         ('lat e lon scambiati', ST_GeogFromText('SRID=4326;POINT(40.353 18.175)'))
)
SELECT nome,
       ST_Covers(q.g, p.g)                     AS covers,
       round(ST_Distance(q.g, p.g)::numeric)   AS metri_dal_poligono
FROM quartiere q, punti p;

-- Output:
--         nome         | covers | metri_dal_poligono
-- ---------------------+--------+--------------------
--  dentro              | t      |                  0
--  sul bordo           | t      |                  0
--  fuori di poco       | f      |                 42
--  lat e lon scambiati | f      |            3249377
-- (4 rows)

I use ST_Covers and not ST_Contains because the documentation recommends the former in general: the latter has the peculiarity that a geometry "does not contain its boundary", so a property on the border of the neighbourhood would not be found. The output shows it: the point on the edge is covered (t), the one 42 metres outside is not. The fourth point repeats the lat/lon inversion: it is not inside the neighbourhood and the database says so correctly, but it is 3,249 km away, that is, on another continent. A distance that large from the polygon on data that should be local is the signal that the coordinates are swapped, and it is a check you can automate at load time.

A product choice that the code cannot make for you: neighbourhood boundaries on portals are often drawn by hand and do not coincide with administrative ones. If you show "Centro zone" but the property is thirty metres from the border, the user perceives it as the centre anyway. A tolerance margin (ST_DWithin on the polygon with a few tens of metres) is often more useful than the exact boundary.

What is not covered and where the rest goes

I did not measure times on real data nor test other indexes (for example hexagonal-grid ones), so I make no performance comparisons. Drawing on a map is a job for the client and has no part in the database. The place of this search in the overall architecture, with the properties table carrying the index and the listings table not, is in the article on the platform architecture; the same concepts applied to buildings, that is, where a sensor or a model element is located, are in BIM; and which points we have the right to show a precise position for, when it is personal data, in privacy and compliance. To show the places found through a panoramic visit, see virtual tours. Text search on the same listings is in the article on full-text search with PostgreSQL; the hexagonal grid, left out of this article, is in H3 geographic indexing; and the map served as vector tiles, instead of thousands of points, is in the article on vector tiles.

What you can do now

You can choose between geometry and geography knowing that it changes the unit of distance, and you can write a radius search with ST_DWithin and a GiST index, checking on the plan that the index gets used. You can order by proximity with <-> and search inside a polygon with ST_Covers without losing the points on the border. And you can recognise the swapped-coordinates defect, which gives no errors but moves properties by kilometres.

In this series, the previous article is Autonomous Property Management with AI Agents.

Sources

The three listings were run on 2026-11-12 with PostgreSQL 17.10 and PostGIS 3.5 on a test machine. The data is generated; the rows read and the distances are those of that run with the seed shown, not a performance measurement.

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