Проверьте, находится ли начальная точка сегмента 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!");
}
Этот код не охватывает все возможности. Например. если отдельные сегменты пересекают многоугольник несколько раз (вход + выход), это не рассматривается в этом примере. В этом случае просто подсчитайте количество пересечений и создайте соответствующее количество линий между точками пересечения.
person
Lars
schedule
14.08.2016