[英]Detect if a LineString / MultiLineString is inside a Polygon or if it intersects it using JTS library
[英]Is (JTS) linestring is entering or exiting a polygon
如果我在 JTS(或一般的某種開放折線)中有一個linestring
,其方向由起點定義,是否有一些聰明的方法可以在與閉合polygon
交點處判斷linestring
是“進入”多邊形還是退出多邊形,或者:
intersection
的坐標polygon
邊緣兩側的linestring
並測試哪個是“in”,哪個是“out”。 如果polygon
具有(不太可能)非常尖銳的內部邊緣,那么這可能會返回不正確的結果。檢查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!");
}
此代碼並未涵蓋所有可能性。 例如,如果單個線段多次與多邊形相交(進入 + 退出),則本示例中不包括在內。 在這種情況下,只需計算交叉點的數量並在交叉點之間創建相應數量的線串。
回答我自己的問題 - 對於任何有類似問題的人。 我最終根據交叉點的數量編寫了一些代碼(因為我已經通過 JTS 獲得了這些代碼)。 想法源於交叉數算法和奇偶規則。
“規則”(我認為沒有例外,可能是錯誤的)是:
作為偽代碼,是這樣的:
Get intersection_points between polyline and closed polygon // using JTS.intersect()
Sort intersection_points along chainage of polyline
if polyline start_point in polygon // using JTS.contains()
first intersect_point is an EXIT, next is an ENTER, EXIT, ENTER and so on alternating along chainage.
else //start point not in polygon
first intersect_point is an ENTER, next is an EXIT, ENTER, EXIT and so on along chainage.
還沒有查看 JTS intersect
源代碼並contains
方法,所以我正在做的事情可能會加倍並在那里進行一些優化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.