BBackend CourseLeroy Labs
0/0
Search the course

Geospatial data with PostGIS

Storing locations as geometry Points, SRID 4326, geometry vs geography, ST_Distance and ST_DWithin, GIST indexes, and Hibernate Spatial/JTS mapping, all from Hostel's map feature.

● advancedHostel-Web-App

The concept

“Find hostels within 2 km of the university gate, sorted by distance” is hard with plain lat/lng columns. The haversine formula in SQL can’t use an index, so it scans everything. PostGIS adds spatial types, functions and indexes to Postgres.

Types and SRIDs

  • SRID 4326 (WGS 84) is the lat/lng coordinate system GPS and Google Maps use.
  • geometry does planar maths, in the units of the SRID (degrees for 4326). It is fast but distances in degrees are meaningless.
  • geography does spherical maths in metres. It is accurate on the earth, and slightly slower.
CREATE EXTENSION postgis;

ALTER TABLE hostels ADD COLUMN location geometry(Point, 4326);
CREATE INDEX idx_hostels_location ON hostels USING GIST (location);

-- note: POINT(longitude latitude), x first
UPDATE hostels SET location = ST_SetSRID(ST_MakePoint(-1.5696, 6.6745), 4326) WHERE id = '...';

Queries

-- hostels within 2000 m of a landmark, nearest first
SELECT h.id, h.name,
       ST_Distance(h.location::geography, l.location::geography) AS metres
FROM hostels h, landmarks l
WHERE l.id = :landmarkId
  AND ST_DWithin(h.location::geography, l.location::geography, :radiusMetres)
ORDER BY metres
LIMIT 20;

-- extract coordinates for the API
SELECT ST_Y(location) AS lat, ST_X(location) AS lng FROM hostels;

ST_DWithin can use the GIST index. ST_Distance(...) < 2000 in a WHERE clause cannot. Always filter with ST_DWithin, then sort by ST_Distance.

Java mapping (Hibernate Spatial + JTS)

import org.locationtech.jts.geom.Point;

@Entity class Hostel {
    @Column(columnDefinition = "geometry(Point,4326)")
    private Point location;
}

GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 4326);
Point p = gf.createPoint(new Coordinate(lng, lat));   // x = lng, y = lat

In your project

Hostel-Web-AppHostel.java · Landmark.java · LandmarkRepository.java · db-init/00-init-extensions.sql
  • Docker image postgis/postgis:18-3.6-alpine, with the extension created in a DB init script.
  • hibernate-spatial + jts-core 1.20.0; Hostel.location and Landmark.location are JTS Points.
  • GIST indexes on both location columns.
  • LandmarkRepository native queries use ST_Distance(h.location::geography, l.location::geography), ST_DWithin(..., :radiusMetres) and ST_Y/ST_X for lat/lng.
  • A SpatialRefSy entity maps the spatial_ref_sys table.

Alternatives

Option Notes
PostGIS (yours) The gold standard; full GIS toolkit
lat/lng columns + haversine Simple, but no index (or bounding-box prefiltering only)
earthdistance / cube extensions Lightweight Postgres option
Redis GEO (GEOADD/GEOSEARCH) Very fast radius queries for live locations (drivers)
Elasticsearch geo_point When combined with full-text search
MongoDB 2dsphere If already on Mongo
  • Axis order. PostGIS is (lng, lat), while many UIs say “lat, lng”. This is the most common GIS bug.
  • GeoJSON is the standard JSON format for geometries, and frontends (Leaflet, Mapbox) consume it.
  • KNN operator <->. ORDER BY location <-> point LIMIT 10 uses GIST for nearest-neighbour queries.
  • Geohash / H3. Grid systems for bucketing locations, useful in caching and analytics.

Check yourself

1. Which uses the GIST index?
2. ST_MakePoint argument order?
3. For metre distances on SRID 4326, cast to…