Skip to content

Instantly share code, notes, and snippets.

@rclark
Last active June 10, 2017 12:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rclark/6123614 to your computer and use it in GitHub Desktop.
Save rclark/6123614 to your computer and use it in GitHub Desktop.
JSTS to create polygons from spaghetti lines. Union on lines is the "planarize" step, and is extremely time-consuming for larg-ish numbers of lines (~300 it takes about 2 seconds per each new line to union).
var jsts = require("jsts"),
_ = require("underscore"),
fs = require("fs");
fs.readFile("/Users/ryan/Desktop/hv-lines.geojson", function (err, data) {
var geojson = JSON.parse(data),
reader = new jsts.io.GeoJSONReader(),
writer = new jsts.io.GeoJSONWriter(),
polygonizer = new jsts.operation.polygonize.Polygonizer(),
geoms = _.map(geojson.features, function (feature) {
return reader.read(feature.geometry);
}),
cleaned = null;
geoms.forEach(function (geom, i, array) {
console.time(i);
if (i === 0) { cleaned = geom; }
else { cleaned = cleaned.union(geom); }
console.timeEnd(i);
});
if (cleaned !== null) {
polygonizer.add(cleaned);
var polygons = polygonizer.getPolygons(),
output = {type: "FeatureCollection", features: []};
polygons.array.forEach(function (poly) {
var f = {type: "Feature", properties: {}, geometry: writer.write(poly)};
output.features.push(f);
});
console.log(JSON.stringify(output));
} else {
console.log("Clean failed");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment