Skip to content

Given a geopoint, find the nearest city using PostGIS (reverse geocode).

License

Notifications You must be signed in to change notification settings

hotosm/pg-nearest-city

Repository files navigation

Simple PostGIS Reverse Geocoder

HOT

Given a geopoint, find the nearest city using PostGIS (reverse geocode).

Publish Docs Publish Test Package version Downloads License


📖 Documentation: https://hotosm.github.io/pg-nearest-city/

🖥️ Source Code: https://github.com/hotosm/pg-nearest-city


Why do we need this?

This package was developed primarily as a basic reverse geocoder for use within web frameworks (APIs) that have an existing PostGIS connection to utilise.

  • The reverse geocoding package in Python here is probably the original and canonincal implementation using K-D tree.
    • However, it's a bit outdated now, with numerous unattended pull requests and uses an unfavourable multiprocessing-based approach.
  • The package here is an excellent revamp of the package above, an likely the best choice in many scenarios.

The K-D tree implementation in Python is performant (see benchmarks) and an excellent choice for scripts.

However, it does leave a large memory footprint of approximately 160Mb to load the K-D tree in memory (see benchmarks).

Once computed, the K-D tree remains in memory! This is an unacceptable compromise for a web server, for such a small amount of functionality, particularly if the web server is run via a container orchestrator as replicas with minimal memory.

As we already have a Postgres database running alongside our webserver, an approach to simply query via pre-loaded data via PostGIS is much more memory efficient (~2Mb) and has an acceptable performance penalty (see benchmarks).

Priorities

  • Lightweight package size.
  • Minimal memory footprint.
  • Reasonably good performance.

How This Package Works

  • geonames.org data.
  • Voronoi polygons based on geopoints.
  • Gzipped data bundled with package.
  • Query the Voronois.

Benchmarks

Testing

Run the tests with:

docker compose run --rm code pytest

About

Given a geopoint, find the nearest city using PostGIS (reverse geocode).

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages