Skip to content

Instantly share code, notes, and snippets.

@a4amaan
Created January 19, 2020 11:42
Show Gist options
  • Save a4amaan/b7b53ddd8be66775d0ee8b8f11b35744 to your computer and use it in GitHub Desktop.
Save a4amaan/b7b53ddd8be66775d0ee8b8f11b35744 to your computer and use it in GitHub Desktop.
Django Haversine formula to find the Nearest Locations.
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