Created
January 19, 2020 11:42
-
-
Save a4amaan/b7b53ddd8be66775d0ee8b8f11b35744 to your computer and use it in GitHub Desktop.
Django Haversine formula to find the Nearest Locations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_nearest_cities(lat, lng, in_radius): | |
earth_radius = 6371 | |
cities = Location.objects.filter().annotate( | |
distance=earth_radius * ACos(Cos(Radians(lat)) * Cos(Radians("latitude")) * Cos( | |
Radians("longitude") - Radians(lng)) + Sin(Radians(lat)) * Sin( | |
Radians('latitude')))).filter(distance__lt=in_radius).order_by("distance") | |
return cities |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment