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
import { city } from "https://esm.town/v/mxdvl/cities";
import { haversine_distance } from "https://esm.town/v/mxdvl/haversine_distance";
type Coordinates = readonly [number, number];
type GeoJSONFeature = {
type: "Feature";
properties: { from: string; to: string | undefined };
geometry: { type: "LineString"; coordinates: readonly Coordinates[] };
};
async function to_line_string(
coordinates: readonly Coordinates[],
en_route = false,
): Promise<Readonly<GeoJSONFeature>> {
// console.log({ coordinates });
const [from, to] = await Promise.all([
city(coordinates.at(0)),
en_route ? undefined : city(coordinates.at(-1)),
]);
// console.log({ from, to });
return {
type: "Feature",
properties: { from, to },
geometry: {
type: "LineString",
coordinates,
},
};
}
export async function* trips(
coordinates: readonly Coordinates[],
distance_threshold = 120,
): AsyncGenerator<GeoJSONFeature> {
let trip = [];
let last_position = coordinates.at(0);
if (!last_position) return;
for (const position of coordinates) {
const distance = haversine_distance(last_position, position, 6371e3);
if (distance > distance_threshold) { trip.push(position); } else if (trip.length > 1) {
yield to_line_string(trip);
trip = [];
} else {
trip = [position];
}
last_position = position;
}
// console.log(trip);
if (trip.length > 1) yield to_line_string(trip, true);
}