Closest locations to a point#
Here’s a PostgreSQL SQL query that returns the closest locations to a point, based on a brute-force approach where the database calculates the distance (in miles) to every single row and then sorts by that distance.
It’s adapted from this StackOverflow answer, which helpfully points out that if you want kilometers rather than miles you can swap the 3959
constant for 6371
instead.
There are much more efficient ways to do this if you are using PostGIS, described in this Nearest-Neighbour Searching tutorial - but if you’re not using PostGIS this works pretty well.
I ran this against a table with over 9,000 rows and got results back in less than 20ms.
1with locations_with_distance as (2 select3 *,4 (5 acos (6 cos (7 radians(%(latitude)s::float)8 ) * cos(9 radians(latitude)10 ) * cos(11 radians(longitude) - radians(%(longitude)s::float)12 ) + sin(13 radians(%(latitude)s::float)14 ) * sin(radians(latitude))15 ) * 395916 ) as distance_miles17 from18 location19)20select21 *22from23 locations_with_distance24order by25 distance_miles26limit27 20
The %(latitude)s
and %(longitude)s
bits are named parameters when working with the Python psycopg2 library - they also work with django-sql-dashboard which I used to prototype this query.
Translated to Django#
Here’s that same formula using the Django ORM:
1from django.db.models import F2from django.db.models.functions import ACos, Cos, Radians, Sin3
4locations = Location.objects.annotate(5 distance_miles = ACos(6 Cos(7 Radians(input_latitude)8 ) * Cos(9 Radians(F('latitude'))10 ) * Cos(11 Radians(F('longitude')) - Radians(input_longitude)12 ) + Sin(13 Radians(input_latitude)14 ) * Sin(Radians(F('latitude')))15 ) * 395916).order_by('distance_miles')[:10]