'Is there a cleaner / simpler way to calculate the edge in a geometry that a line crosses?
In the code below it is fairly simple to check does the line cross into the geometry or not - it's also trivial to work out the coordinate that the line crosses into the geometry at. However (and I've tried quite a few different ways), it seems way more convoluted to work out which line segment it is on.
final GeometryFactory fact = new GeometryFactory();
// The thing we are testing.
final Geometry gTestPoly = fact.createPolygon(new Coordinate[] { new Coordinate(0, 0),
new Coordinate(0, 10), new Coordinate(10, 10),
new Coordinate(10, 0), new Coordinate(0, 0)}); // a square
// Preconditions
final Coordinate cOutsideThePoly = new Coordinate(-5, 5);
final Coordinate cInsideThePoly = new Coordinate(5, 5);
final Geometry gOutsideThePoly = fact.createPoint(cOutsideThePoly);
final Geometry gInsideThePoly = fact.createPoint(cInsideThePoly);
assertTrue(gTestPoly.contains(gInsideThePoly));
assertFalse(gTestPoly.contains(gOutsideThePoly));
final Geometry gIntersectingLine = fact.createLineString(new Coordinate[] {cOutsideThePoly, cInsideThePoly}); // a line that crosses into the square
final LineSegment lIntersectingLine = new LineSegment(cOutsideThePoly, cInsideThePoly);
// Easy - it crosses the boundary on just 1 edge.
assertTrue(gIntersectingLine.crosses(gTestPoly));
// But if I want to see which edge/line segment my intersecting line segment crosses at ?? [this feels quite clunky..]
final Geometry gLineVersionOfTestPoly = LinearComponentExtracter.getGeometry(gTestPoly, true);
final LinearIterator iSegments = new LinearIterator(gLineVersionOfTestPoly);
final LineSegment forTest = new LineSegment();
while (iSegments.hasNext()) {
final Coordinate from = iSegments.getSegmentStart();
final Coordinate to = iSegments.getSegmentEnd();
forTest.setCoordinates(from, to);
if (forTest.intersection(lIntersectingLine) != null) {
System.err.println("Matching " + forTest);
}
iSegments.next(); // move to next step.
}
I get what I expect for output -
Matching LINESTRING( 0.0 0.0, 0.0 10.0)
Yes understand could just grab all the coordinates (via getCoordinates()
) and check line segments like that - again seems like I've missed the magic simple method..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|