Skip to content

Instantly share code, notes, and snippets.

@ncole458
Last active March 8, 2023 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ncole458/9a934dc937e78d2ba268 to your computer and use it in GitHub Desktop.
Save ncole458/9a934dc937e78d2ba268 to your computer and use it in GitHub Desktop.
Django queryset for objects within X long/lat radius
# Simple version of Django queryset for objects within X long/lat radius
import math
def get_queryset(self):
user = self.request.user
lat = self.request.query_params.get('lat', None)
lon = self.request.query_params.get('long', None)
if lat and lon:
lat = float(lat)
lon = float(lon)
R = 6378.1 # earth radius
distance = 10 # distance in km
lat1 = lat - math.degrees(distance / R)
lat2 = lat + math.degrees(distance / R)
long1 = lon - math.degrees(distance / R / math.cos(math.degrees(lat)))
long2 = lon + math.degrees(distance / R / math.cos(math.degrees(lat)))
queryset = UserDetail.objects.filter(current_lat__gte=lat1, current_lat__lte=lat2)\
.filter(current_long__gte=long1, current_long__lte=long2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment