[英]How to check if a LineString intersects a LineString (or Polygon)
[英]How to check if a linestring intersects a polygon in Java
我正在嘗試生成一個避免地圖上出現多個polygons
的linestring
,但為了做到這一點,我需要一種方法來檢查linestring
是否與polygon
相交。 最初我嘗試使用這種方法,它接受linestring
端點的坐標和多邊形列表以避免:
public boolean Intersects(Double endPosLng, Double endPosLat, List<Polygon> polygons) {
Boolean intersects = false;
Point end = Point.fromLngLat(endPosLng, endPosLat);
for (Polygon poly : polygons) {
if (TurfJoins.inside(end, poly)) {
intersects = true;
}
}
return intersects;
}
但TurfJoins.inside(end, polygon)
只考慮的終點linestring
,所以線可切割的多邊形的角部(參見下圖),但仍最終多邊形外部,從而所述方法不檢測它作為一個路口。
我想到了在以前的坐標傳送linestring
生成的段linestring
,但我不認為Mapbox有一個方法來檢查,如果一個linestring
相交的polygon
的任何一點。
如何檢查linestring
是否與多邊形相交?
首先,您的Point
似乎是錯誤的點類。 您應該使用java.awt.Point
,而不是您正在使用的任何 GeoJSON 庫中的Point
。 接下來,如果您的多邊形沒有大量邊,您可以簡單地檢查該線是否與任何邊相交:
import java.awt.geom.Line2D;
import java.awt.Polygon;
class Intersects {
public static boolean intersects(Line2D line, Polygon poly) {
for (int i = 0; i < poly.npoints; i ++) {
int nextI = (i + 1) % poly.npoints;
Line2D edge = new Line2D.Double(poly.xpoints[i], poly.ypoints[i], poly.xpoints[nextI], poly.ypoints[nextI]);
if (line.intersectsLine(edge)) {
return true;
}
}
return false;
}
// test cases
public static void main(String[] args) {
Polygon poly = new Polygon(
new int[]{0, 1, 1, 0},
new int[]{0, 0, 1, 1},
4
); // square of edge length 1 with bottom-left corner at (0, 0)
Line2D[] lines = new Line2D[]{
new Line2D.Double(-0.5, -0.5, 0.5, 0.5), // true
new Line2D.Double(0.5, 2.0, 0.5, 3.0), // false
new Line2D.Double(0.5, -0.1, 1.2, 0.5) // true
};
for (Line2D line: lines) {
System.out.printf("%s: %b\n", line, intersects(line, poly));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.