Skip to content

Instantly share code, notes, and snippets.

@rclark
Last active March 11, 2018 19:41
Show Gist options
  • Select an option

  • Save rclark/6205437 to your computer and use it in GitHub Desktop.

Select an option

Save rclark/6205437 to your computer and use it in GitHub Desktop.
Example of "cleaning" a line network using JSTS to create a properly noded segment network (i.e. nodes at every intersection between segments).
var jsts = require("jsts"),
fs = require("fs"),
javascript = require("javascript.util"),
assert = require("assert"),
lines = [
"LINESTRING(-110.5 32.1,-110.45 32.2,-110.4 32.1)",
"LINESTRING(-110.5 32.25,-110.45 32.2,-110.45 32.15,-110.4 32.25)"
],
expected = [
"LINESTRING(-110.5 32.1,-110.45 32.2)",
"LINESTRING(-110.45 32.2,-110.4375 32.175)",
"LINESTRING(-110.4375 32.175,-110.4 32.1)",
"LINESTRING(-110.5 32.25,-110.45 32.2)",
"LINESTRING(-110.45 32.2,-110.45 32.15,-110.4375 32.175)",
"LINESTRING(-110.4375 32.175,-110.4 32.25)"
],
calculated = [];
var reader = new jsts.io.WKTReader(),
writer = new jsts.io.WKTWriter(),
noder = new jsts.noding.MCIndexNoder(),
intersector = new jsts.noding.IntersectionAdder(new jsts.algorithm.RobustLineIntersector()),
factory = new jsts.geom.GeometryFactory(),
segments = new javascript.util.ArrayList();
// Convert the WKT Lines into jsts NodedSegmentStrings
lines.forEach(function (line) {
var feature = reader.read(line);
segments.add(new jsts.noding.NodedSegmentString(feature.points));
});
// Clean the network of lines
noder.setSegmentIntersector(intersector);
noder.computeNodes(segments);
var cleanedSegments = noder.getNodedSubstrings();
// Extract jsts LineStrings from the cleaned segments
var i = cleanedSegments.iterator();
while (i.hasNext()) {
var segment = i.next(),
coords = segment.getCoordinates(),
line = factory.createLineString(coords);
calculated.push(writer.write(line));
}
// Check that it worked
assert.equal(expected.length, calculated.length, "The noder did not produce the expected number of line segments");
expected.forEach(function (expectedLine) {
assert(calculated.indexOf(expectedLine) !== -1, "The noder did not produce the expected line segment: " + expectedLine);
});
@vittrup88
Copy link
Copy Markdown

Hi,

I tried to get JSTS to clean some lines with your script. It seems there is a problem. I'm using JSTS in browser, but i get a problem at noder.setSegmentIntersector(intersector)
I get this error:
Uncaught TypeError: inputSegStrings.iterator is not a function

Have there been any changes or can you tell me why this might not work anymore?

//Anders

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment