Last active
March 8, 2023 10:11
-
-
Save ncole458/9a934dc937e78d2ba268 to your computer and use it in GitHub Desktop.
Django queryset for objects within X long/lat radius
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
# 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