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
53
54
55
56
57
58
59
|
import json
import math
def calculate_bearing(lat1, lon1, lat2, lon2):
d_lon = lon2 - lon1
x = math.cos(math.radians(lat2)) * math.sin(math.radians(d_lon))
y = math.cos(math.radians(lat1)) * math.sin(math.radians(lat2)) - \
math.sin(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.cos(math.radians(d_lon))
bearing = math.atan2(x, y)
bearing = math.degrees(bearing)
bearing = (bearing + 360) % 360
return bearing
def calculate_distance(lat1, lon1, lat2, lon2):
R = 6371000 # Earth's radius in meters
d_lat = math.radians(lat2 - lat1)
d_lon = math.radians(lon2 - lon1)
a = math.sin(d_lat / 2) * math.sin(d_lat / 2) + \
math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * \
math.sin(d_lon / 2) * math.sin(d_lon / 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
def calculate_timestamp(data, current_index):
if current_index == 0:
return 0
else:
prev_timestamp = calculate_timestamp(data, current_index - 1)
return prev_timestamp + data[current_index-1]['distance'] / data[current_index]['speed']
def process_route(input_filename, output_filename):
with open(input_filename, 'r') as infile:
data = json.load(infile)
output_data = []
for i in range(len(data)):
if i == len(data) - 1:
data[i]['bearing'] = calculate_bearing(data[i]['latitude'], data[i]['longitude'],
data[i-1]['latitude'], data[i-1]['longitude'])
else:
bearing = calculate_bearing(data[i]['latitude'], data[i]['longitude'],
data[i+1]['latitude'], data[i+1]['longitude'])
data[i]['bearing'] = bearing
data[i]['distance'] = calculate_distance(data[i]['latitude'], data[i]['longitude'],
data[i+1]['latitude'], data[i+1]['longitude'])
data[i]['timestamp'] = calculate_timestamp(data, i)
output_data.append(data[i])
for d in output_data:
d.pop("distance", None)
with open(output_filename, 'w') as outfile:
json.dump(output_data, outfile, indent=2)
|