This repository has been archived by the owner on Feb 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cellFromGeolocations.ts
62 lines (55 loc) · 1.93 KB
/
cellFromGeolocations.ts
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
60
61
62
import { Option, none, some } from 'fp-ts/lib/Option'
import { earthTunnelDistance } from './tunnelDistance'
const byNumericValue = (a: number, b: number) => a - b
const sum = (total: number, v: number) => total + v
export type Point = { lat: number; lng: number }
export type CellGeoLocation = Point & { accuracy: number }
/**
* Calculates a cell geo location based on a list of geo locations:
*
* - the center is the average of all given locations (within a configurable percentile)
* - the diameter returned is a circle that includes all given locations (within a configurable percentile), but at least `minCellDiameterInMeters`.
*/
export const cellFromGeolocations = ({
minCellDiameterInMeters,
percentile,
}: {
minCellDiameterInMeters: number
percentile: number
}) => (locations: Point[]): Option<CellGeoLocation> => {
if (!locations.length) return none
if (locations.length === 1)
return some({
lat: locations[0].lat,
lng: locations[0].lng,
accuracy: minCellDiameterInMeters,
})
// Location is average of the given percentile of all positions
const lats = locations.map(({ lat }) => lat + 90).sort(byNumericValue)
const lngs = locations.map(({ lng }) => lng + 180).sort(byNumericValue)
const entriesToConsider = Math.round(locations.length * percentile)
const start = Math.floor((locations.length - entriesToConsider) / 2)
const center = {
lat:
lats.slice(start, start + entriesToConsider).reduce(sum, 0) /
entriesToConsider -
90,
lng:
lngs.slice(start, start + entriesToConsider).reduce(sum, 0) /
entriesToConsider -
180,
}
// Calculate largest distance, but filter out the given percentile
const distances = locations
.map(d => earthTunnelDistance(center, d))
.sort(byNumericValue)
const significantLargestEntry = Math.floor(locations.length * percentile)
const accuracy = Math.max(
minCellDiameterInMeters,
distances[significantLargestEntry] * 2,
)
return some({
...center,
accuracy,
})
}