forked from perliedman/geojson-path-finder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topology.js
73 lines (60 loc) · 2.11 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
var explode = require('@turf/explode'),
roundCoord = require('./round-coord');
module.exports = topology;
function geoJsonReduce(geojson, fn, seed) {
if (geojson.type === 'FeatureCollection') {
return geojson.features.reduce(function reduceFeatures(a, f) {
return geoJsonReduce(f, fn, a);
}, seed);
} else {
return fn(seed, geojson);
}
}
function geoJsonFilterFeatures(geojson, fn) {
var features = [];
if (geojson.type === 'FeatureCollection') {
features = features.concat(geojson.features.filter(fn));
}
return {
type: 'FeatureCollection',
features: features
};
}
function isLineString(f) {
return f.geometry.type === 'LineString';
}
function topology(geojson, options) {
options = options || {};
var keyFn = options.keyFn || function defaultKeyFn(c) {
return c.join(',');
},
precision = options.precision || 1e-5;
var lineStrings = geoJsonFilterFeatures(geojson, isLineString);
var explodedLineStrings = explode.default(lineStrings);
var vertices = explodedLineStrings.features.reduce(function buildTopologyVertices(cs, f, i, fs) {
var rc = roundCoord(f.geometry.coordinates, precision);
cs[keyFn(rc)] = f.geometry.coordinates;
if (i % 1000 === 0 && options.progress) {
options.progress('topo:vertices', i, fs.length);
}
return cs;
}, {}),
edges = geoJsonReduce(lineStrings, function buildTopologyEdges(es, f, i, fs) {
f.geometry.coordinates.forEach(function buildLineStringEdges(c, i, cs) {
if (i > 0) {
var k1 = keyFn(roundCoord(cs[i - 1], precision)),
k2 = keyFn(roundCoord(c, precision));
es.push([k1, k2, f.properties]);
}
});
if (i % 1000 === 0 && options.progress) {
options.progress('topo:edges', i, fs.length);
}
return es;
}, []);
return {
vertices: vertices,
edges: edges
};
}