检查一段的起点linestring
是在多边形内部还是外部,以确定它是进入还是退出polygon
. 简单的代码示例:
// some demo polygon + line
Polygon polygon = new GeometryFactory().createPolygon(new Coordinate[]{new Coordinate(1,1), new Coordinate(6,1), new Coordinate(6,6), new Coordinate(1,6), new Coordinate(1,1)});
LineString line = new GeometryFactory().createLineString(new Coordinate[]{new Coordinate(0, 0), new Coordinate(5,5), new Coordinate(10,5)});
// check for intersection in the first place
if(line.intersects(polygon)){
System.out.println("line intersects polygon!");
// iterate over all segments of the linestring and check for intersections
for(int i = 1; i < line.getNumPoints(); i++){
// create line for current segment
LineString currentSegment = new GeometryFactory().createLineString(new Coordinate[]{line.getCoordinates()[i-1], line.getCoordinates()[i]});
// check if line is intersecting with ring
if(currentSegment.intersects(polygon)){
// segment is entering the ring if startpoint is outside the ring
if(!polygon.contains(currentSegment.getStartPoint())){
System.out.println("This segment is entering the polygon -> ");
System.out.println(currentSegment.toText());
// startpoint is inside the ring
}
if (polygon.contains(currentSegment.getStartPoint())) {
System.out.println("This segment is exiting the polygon -> ");
System.out.println(currentSegment.toText());
}
}
}
} else {
System.out.println("line is not intersecting the polygon!");
}
此代码并未涵盖所有可能性。例如,如果单个线段与多边形多次相交(进入 + 退出),则此示例未涵盖此内容。在这种情况下,只需计算交叉点的数量并在交叉点之间创建相应数量的线串。