39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
import math
|
|
from manage_events.models import Event, Venue
|
|
|
|
|
|
def haversine(lon1, lat1, lon2, lat2):
|
|
"""
|
|
Calculate the great circle distance in kilometers between two points
|
|
on the earth (specified in decimal degrees)
|
|
"""
|
|
# convert decimal degrees to radians
|
|
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
|
|
|
|
# haversine formula
|
|
dlon = lon2 - lon1
|
|
dlat = lat2 - lat1
|
|
a = (
|
|
math.sin(dlat / 2) ** 2
|
|
+ math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
|
|
)
|
|
c = 2 * math.asin(math.sqrt(a))
|
|
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
|
|
return c * r
|
|
|
|
|
|
def filter_events_by_location(user_lat, user_lon, radius_km=10):
|
|
venues_within_radius = []
|
|
|
|
# Check each venue to see if it's within the radius
|
|
for venue in Venue.objects.filter(deleted=False, active=True):
|
|
print("venue: ", venue)
|
|
distance = haversine(user_lon, user_lat, venue.longitude, venue.latitude)
|
|
print("distance: ", distance)
|
|
if distance <= radius_km:
|
|
venues_within_radius.append(venue.id)
|
|
print("venues_within_radius: ", venues_within_radius)
|
|
# Filter events based on the venues within the radius
|
|
events = Event.objects.filter(venue__id__in=venues_within_radius)
|
|
return events
|