-
Notifications
You must be signed in to change notification settings - Fork 0
/
stations.py
52 lines (40 loc) · 1.31 KB
/
stations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import sqlite3
from math import sin, cos, sqrt, atan2, radians
import operator
def dict_from_row(row):
return dict(zip(row.keys(), row))
def get_stations(conn):
conn.row_factory = sqlite3.Row
c = conn.cursor()
rows = c.execute("SELECT * FROM stations")
returndata = []
for row in rows:
returndata.append(dict_from_row(row))
return returndata
def get_station(conn, code):
conn.row_factory = sqlite3.Row
c = conn.cursor()
params = (code.upper(),)
rows = c.execute("SELECT * FROM stations WHERE code = ? LIMIT 1", params)
returndata = False
for row in rows:
returndata = dict_from_row(row)
return returndata
def nearest_stations(conn, lat, lon, max_entries):
sd = get_stations(conn)
lat1 = radians(lat)
lon1 = radians(lon)
# approximate radius of earth in km
R = 6373.0
for station in sd:
lat2 = radians(station['lat'])
lon2 = radians(station['lon'])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
station['distance'] = distance
sd.sort(key=operator.itemgetter('distance'))
returndata = {"status": "OK", "stations": sd[:max_entries]}
return returndata