public Set<Location> intersections(final Segment candidate) { final Set<Location> result = new HashSet<>(); final List<Segment> segments = this.segments(); segments.forEach(segment -> { final Location intersection = segment.intersection(candidate); if (intersection != null) { result.add(intersection); } }); return result; }
/** * @return True if the {@link PolyLine} self intersects at locations other than shape points. */ public boolean selfIntersects() { // See comments on algorithm in selfIntersections() final boolean isPolygon = this instanceof Polygon; final List<Segment> segments = this.segments().stream() .filter(segment -> !segment.isPoint()).collect(Collectors.toList()); for (int i = 0; i < segments.size() - 2; i++) { final int limit = isPolygon && i == 0 ? segments.size() - 1 : segments.size(); for (int j = i + 2; j < limit; j++) { if (segments.get(i).intersection(segments.get(j)) != null) { return true; } } } return false; }
final Location intersection = segments.get(i).intersection(segments.get(j));
@Test public void testIntersection() { Assert.assertEquals(null, new Segment(Location.TEST_1, Location.TEST_2) .intersection(new Segment(Location.TEST_4, Location.TEST_3))); Assert.assertEquals(false, new Segment(Location.TEST_1, Location.TEST_2) .intersects(new Segment(Location.TEST_4, Location.TEST_3))); Assert.assertEquals( new Location(Latitude.degrees(37.3273389), Longitude.degrees(-122.0287109)), new Segment(Location.TEST_1, Location.TEST_3) .intersection(new Segment(Location.TEST_4, Location.TEST_2))); Assert.assertEquals(true, new Segment(Location.TEST_1, Location.TEST_3) .intersects(new Segment(Location.TEST_4, Location.TEST_2))); } }