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.
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.
geometrydoes planar maths, in the units of the SRID (degrees for 4326). It is fast but distances in degrees are meaningless.geographydoes 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-App
Hostel.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.locationandLandmark.locationare JTSPoints.- GIST indexes on both location columns.
LandmarkRepositorynative queries useST_Distance(h.location::geography, l.location::geography),ST_DWithin(..., :radiusMetres)andST_Y/ST_Xfor lat/lng.- A
SpatialRefSyentity maps thespatial_ref_systable.
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 |
Related concepts you must know
- 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 10uses 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…