Skip to main content
The earthdistance extension in PostgreSQL provides functions for calculating great-circle distances between points on Earth. It is useful for applications that require geospatial distance calculations, such as location-based services and mapping applications. Your Nile database arrives with earthdistance extension and its dependency cube already enabled, so there’s no need to run create extension.

Creating and Populating locations Table

Before performing distance calculations, let’s create a sample table to store latitude and longitude values:

Calculating Distance Between Two Points

To compute the great-circle distance between two points (given in latitude and longitude in degrees), use the earth_distance() function:
This returns the approximate distance in meters between San Francisco and New York.

Finding Locations Within a Given Radius

To find all locations within 1000 km of San Francisco:

Limitations

  • earthdistance assumes a spherical Earth model, which may introduce minor inaccuracies.
  • Distance calculations are approximate and may not be suitable for high-precision geospatial applications.
  • Requires both cube and earthdistance extensions to be installed.

Removing an Index

If you need to remove the spatial index:

Conclusion

The earthdistance extension in PostgreSQL simplifies great-circle distance calculations for geographic coordinates. It is useful for applications needing fast location-based searches and distance queries. For more details, refer to the PostgreSQL documentation.