01: package com.vividsolutions.jtsexample.technique;
02:
03: import com.vividsolutions.jts.geom.*;
04: import com.vividsolutions.jts.io.WKTReader;
05: import java.util.*;
06:
07: /**
08: * Shows a technique for identifying the location of self-intersections
09: * in a non-simple LineString.
10: *
11: * @version 1.7
12: */
13:
14: public class LineStringSelfIntersections {
15:
16: public static void main(String[] args) throws Exception {
17: WKTReader rdr = new WKTReader();
18:
19: LineString line1 = (LineString) (rdr
20: .read("LINESTRING (0 0, 10 10, 20 20)"));
21: showSelfIntersections(line1);
22: LineString line2 = (LineString) (rdr
23: .read("LINESTRING (0 40, 60 40, 60 0, 20 0, 20 60)"));
24: showSelfIntersections(line2);
25:
26: }
27:
28: public static void showSelfIntersections(LineString line) {
29: System.out.println("Line: " + line);
30: System.out.println("Self Intersections: "
31: + lineStringSelfIntersections(line));
32: }
33:
34: public static Geometry lineStringSelfIntersections(LineString line) {
35: Geometry lineEndPts = getEndPoints(line);
36: Geometry nodedLine = line.union(lineEndPts);
37: Geometry nodedEndPts = getEndPoints(nodedLine);
38: Geometry selfIntersections = nodedEndPts.difference(lineEndPts);
39: return selfIntersections;
40: }
41:
42: public static Geometry getEndPoints(Geometry g) {
43: List endPtList = new ArrayList();
44: if (g instanceof LineString) {
45: LineString line = (LineString) g;
46:
47: endPtList.add(line.getCoordinateN(0));
48: endPtList.add(line.getCoordinateN(line.getNumPoints() - 1));
49: } else if (g instanceof MultiLineString) {
50: MultiLineString mls = (MultiLineString) g;
51: for (int i = 0; i < mls.getNumGeometries(); i++) {
52: LineString line = (LineString) mls.getGeometryN(i);
53: endPtList.add(line.getCoordinateN(0));
54: endPtList.add(line
55: .getCoordinateN(line.getNumPoints() - 1));
56: }
57: }
58: Coordinate[] endPts = CoordinateArrays
59: .toCoordinateArray(endPtList);
60: return (new GeometryFactory()).createMultiPoint(endPts);
61: }
62:
63: }
|