blob: c716063a1c4e851aba8a0c6add712c2e05833eb9 (
plain) (
blame)
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
63
64
|
const CheapRuler = require('cheap-ruler')
const ruler = new CheapRuler(-37, 'meters')
/**
* Cluster points together where within threshold distance.
*
* @param {Array} features - GeoJSON Point Features
* @param {number} thresholdDistance - Maximum distance between points to cluster together
*
* @returns {Array} clusters, where unclustered features are returned as single feature clusters
*/
module.exports = (features, thresholdDistance) => {
// Array of clusters where each cluster is a Set of feature index's
const clusters = []
features.map((a, ai) => {
features.map((b, bi) => {
// skip comparing with self
if (ai === bi) return
const distance = ruler.distance(a.geometry.coordinates, b.geometry.coordinates)
if (distance < thresholdDistance) {
// link into a cluster
let addedToExistingCluster = false
clusters.forEach((cluster, i) => {
if (cluster.has(ai) || cluster.has(bi)) {
// insert into this cluster
clusters[i].add(ai)
clusters[i].add(bi)
addedToExistingCluster = true
}
})
if (!addedToExistingCluster) {
// create a new cluster
const newCluster = new Set()
newCluster.add(ai)
newCluster.add(bi)
clusters.push(newCluster)
}
} // else don't cluster together
})
})
// result is array of clusters, including non-clustered features as single item clusters
const result = clusters.map(cluster => {
return Array.from(cluster).map(index => {
return features[index]
})
})
// find features not clustered
features.map((feature, index) => {
// if feature not a cluster, return as an single item cluster
const featureInACluster = clusters.map(cluster => cluster.has(index)).reduce((acc, cur) => acc || !!cur, false)
if (!featureInACluster) {
result.push([feature])
}
})
return result
}
|