26 lines
1.4 KiB
Python
26 lines
1.4 KiB
Python
from collections import defaultdict
|
|
from datetime import date as date_type
|
|
import h3
|
|
from events.models import Event
|
|
|
|
def map_data(params):
|
|
qs=Event.objects.filter(status=Event.Status.APPROVED).exclude(h3_cell='')
|
|
source=params.get('source')
|
|
if source in Event.Source.values: qs=qs.filter(source=source)
|
|
date=params.get('date')
|
|
if date:
|
|
try: date_type.fromisoformat(date)
|
|
except ValueError: return []
|
|
qs=qs.filter(occurred_at__date=date)
|
|
cells=defaultdict(lambda:{'occurrences':0,'events':0,'dates':set(),'sources':set(),'visual_confirmed':None,'directions':[]})
|
|
for event in qs:
|
|
cell=cells[event.h3_cell];cell['occurrences']+=event.occurrences;cell['events']+=1;cell['dates'].add(event.occurred_at.date().isoformat());cell['sources'].add(event.source)
|
|
if event.visually_confirmed is True: cell['visual_confirmed']=True
|
|
if event.direction_degrees is not None: cell['directions'].append({'degrees':event.direction_degrees,'accuracy_degrees':event.direction_accuracy_degrees})
|
|
result=[]
|
|
for key,item in cells.items():
|
|
try: boundary=[[lat,lon] for lat,lon in h3.cell_to_boundary(key)];center=list(h3.cell_to_latlng(key))
|
|
except (ValueError,h3.H3Error): continue
|
|
result.append({'h3_cell':key,'boundary':boundary,'center':center,'occurrences':item['occurrences'],'events':item['events'],'dates':sorted(item['dates']),'sources':sorted(item['sources']),'visually_confirmed':item['visual_confirmed'],'directions':item['directions']})
|
|
return result
|