forked from perliedman/geojson-path-finder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocessor.js
78 lines (69 loc) · 2.52 KB
/
preprocessor.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
74
75
76
77
78
'use strict';
var topology = require('./topology'),
compactor = require('./compactor'),
distance = require('@turf/distance').default,
roundCoord = require('./round-coord'),
point = require('turf-point');
module.exports = function preprocess(graph, options) {
options = options || {};
var weightFn = options.weightFn || function defaultWeightFn(a, b) {
return distance(point(a), point(b));
},
topo;
if (graph.type === 'FeatureCollection') {
// Graph is GeoJSON data, create a topology from it
topo = topology(graph, options);
} else if (graph.edges) {
// Graph is a preprocessed topology
topo = graph;
}
var graph = topo.edges.reduce(function buildGraph(g, edge, i, es) {
var a = edge[0],
b = edge[1],
props = edge[2],
w = weightFn(topo.vertices[a], topo.vertices[b], props),
makeEdgeList = function makeEdgeList(node) {
if (!g.vertices[node]) {
g.vertices[node] = {};
if (options.edgeDataReduceFn) {
g.edgeData[node] = {};
}
}
},
concatEdge = function concatEdge(startNode, endNode, weight) {
var v = g.vertices[startNode];
v[endNode] = weight;
if (options.edgeDataReduceFn) {
g.edgeData[startNode][endNode] = options.edgeDataReduceFn(options.edgeDataSeed, props);
}
};
if (w) {
makeEdgeList(a);
makeEdgeList(b);
if (w instanceof Object) {
if (w.forward) {
concatEdge(a, b, w.forward);
}
if (w.backward) {
concatEdge(b, a, w.backward);
}
} else {
concatEdge(a, b, w);
concatEdge(b, a, w);
}
}
if (i % 1000 === 0 && options.progress) {
options.progress('edgeweights', i,es.length);
}
return g;
}, {edgeData: {}, vertices: {}});
var compact = compactor.compactGraph(graph.vertices, topo.vertices, graph.edgeData, options);
return {
vertices: graph.vertices,
edgeData: graph.edgeData,
sourceVertices: topo.vertices,
compactedVertices: compact.graph,
compactedCoordinates: compact.coordinates,
compactedEdges: options.edgeDataReduceFn ? compact.reducedEdges : null
};
};