Debian Codegraph @

topojson/bin/topojson-group

raw
1 #!/usr/bin/env node
2
3 var fs = require("fs");
4
5 var d3 = require("d3"),
6 optimist = require("optimist"),
7 rw = require("rw").dash,
8 topojson = require("../"),
9 mergeProperties = require("../lib/topojson/merge-properties");
10
11 var argv = optimist
12 .usage("Usage: \033[1mtopojson-group\033[0m [options] -- file\n\n"
13
14 + "Version: " + topojson.version + "\n\n"
15
16 + "Groups geometries with the same id into multi-geometries.")
17
18 .options("o", {
19 alias: "out",
20 describe: "output TopoJSON file name",
21 default: "-",
22 })
23 .options("p", {
24 alias: "properties",
25 describe: "properties to preserve in grouped objects (if consistent)",
26 default: true
27 })
28 .options("help", {
29 describe: "display this helpful message",
30 type: "boolean",
31 default: false
32 })
33 .check(function(argv) {
34 if (argv.help) return;
35 if (argv._.length > 1) throw new Error("at most one input file allowed");
36 if (!argv._.length) argv._ = ["-"];
37 })
38 .argv;
39
40 if (argv.help) return optimist.showHelp();
41
42 var topology = JSON.parse(rw.readFileSync(argv._[0], "utf8"));
43
44 for (var key in topology.objects) {
45 var object = topology.objects[key];
46
47 if (object.geometries) {
48 var groupById = d3.map(),
49 groups = [];
50
51 object.geometries.forEach(function(geometry) {
52 var group = groupById.get(geometry.id);
53 if (group) group.push(geometry);
54 else groups.push(groupById.set(geometry.id, [geometry]));
55 });
56
57 object.geometries = groups.map(function(group) {
58 return group.length === 1 ? group[0] : multi(group);
59 });
60 }
61 }
62
63 // Output JSON.
64 rw.writeFileSync(argv.o, JSON.stringify(topology), "utf8");
65
66 function multi(geometries) {
67 var type = geometries[0].type,
68 coordinates = /Point$/.test(type) ? "coordinates" : "arcs",
69 array = [];
70
71 geometries.forEach(function(geometry) {
72 if (/^Multi/.test(geometry.type)) {
73 geometry[coordinates].forEach(function(coordinates) { array.push(coordinates); });
74 } else {
75 array.push(geometry[coordinates]);
76 }
77 });
78
79 var geometry = {
80 id: geometries[0].id,
81 type: /^Multi/.test(type) ? type : "Multi" + type
82 };
83
84 geometry[coordinates] = array;
85
86 if (argv.p) {
87 var properties = mergeProperties();
88 geometries.forEach(properties.merge);
89 properties.apply(geometry);
90 }
91
92 return geometry;
93 }