DEV Community

David S
David S

Posted on

Postgres earthdistance

One PostgreSQL feature I recently revisited is earthdistance, a nice reminder that not every problem involving latitude and longitude requires a full GIS stack.

The earthdistance extension provides a straightforward way to calculate great-circle distances between locations on Earth. Combined with PostgreSQL’s cube extension, ll_to_earth() converts latitude and longitude into a representation that earth_distance() can use to calculate distance in meters.

It also provides earth_box(), which is useful for nearby-location searches. An indexed bounding-box search can quickly narrow the candidates, followed by earth_distance() to determine which points actually fall within the desired radius.

There’s also a simpler approach using PostgreSQL’s built-in point type and the <@> operator, which returns distances in statute miles.

There are limitations: earthdistance models Earth as a sphere, and it isn’t a replacement for PostGIS when you need complex geometries, coordinate systems, spatial relationships, or serious GIS analysis.

But that’s exactly why I like it.

If your application just needs to answer something like “Which locations are within 10 miles of this point?”, PostgreSQL may already have all the geospatial functionality you need.

Top comments (0)