java - 如何检查线串是否与Java中的多边形相交
问题描述
我正在尝试生成一个linestring
避免polygons
在地图上出现多个的 a,但为了做到这一点,我需要一种方法来检查 a 是否linestring
与 a 相交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 没有一种方法可以检查 a 是否在任何点与 alinestring
相交。polygon
如何检查是否linestring
与多边形相交?
解决方案
首先,您Point
似乎是错误的点类。您应该使用java.awt.Point
,而不是Point
来自您正在使用的任何 GeoJSON 库。接下来,如果您的多边形没有大量边,您可以简单地检查线是否与任何边相交:
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));
}
}
}
推荐阅读
- javascript - i18n-next 绑定不适用于深度 JSON 对象?
- python - 根据标签创建热图并在其上绘制三条不同的线
- html - nosuchelement:无法定位元素:{"method":"xpath","selector":"//body/div[@id='root']/div[1]/div[1]/div[1]/ div[1]/div[1]/div[1]/div[2]/div[4]"}
- java - 通过远程 JVM 在 Intellij IDEA 中进行 Maven 调试不会通过 Step Over/Into btns 遍历代码
- sorting - 苏禄智能字段类型排序顺序?
- react-native - React-Native:文本在不同手机中呈现不同
- kubernetes - GKE 单 ip 负载平衡器重叠端口
- python - 为什么在使用 pymysql 时必须重新连接数据库才能获取更新的数据库数据?
- python - 在 Api URL 中如何在 Django 中增加页码
- javascript - 使用节点 js 过滤对象键和值