forked from perliedman/geojson-path-finder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopology.js
50 lines (44 loc) · 1.41 KB
/
topology.js
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
var explode = require('turf-explode');
module.exports = topology;
function geoJsonReduce(geojson, fn, seed) {
if (geojson.type === 'FeatureCollection') {
return geojson.features.reduce(function(a, f) {
return geoJsonReduce(f, fn, a);
}, seed);
} else {
return fn(seed, geojson);
}
}
function topology(geojson, options) {
options = options || {};
var keyFn = options.keyFn || function(c) {
return c.join(',');
},
precision = options.precision || 1e-5,
roundCoord = function(c) {
return c.map(function(c) {
return Math.round(c / precision) * precision;
});
};
var vertices = explode(geojson).features.reduce(function(cs, f) {
var rc = roundCoord(f.geometry.coordinates);
cs[keyFn(rc)] = rc;
return cs;
}, {}),
edges = geoJsonReduce(geojson, function(es, f) {
if (f.geometry.type === 'LineString') {
f.geometry.coordinates.forEach(function(c, i, cs) {
if (i > 0) {
var k1 = keyFn(roundCoord(cs[i - 1])),
k2 = keyFn(roundCoord(c));
es.push([k1, k2]);
}
});
}
return es;
}, []);
return {
vertices: vertices,
edges: edges
};
}