有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mapbox如何在Java中检查线字符串是否与多边形相交

我正在尝试生成一个linestring以避免在一个映射上出现多个polygons,但是为了做到这一点,我需要一个方法来检查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的端点,因此直线可能会切割多边形的角(请参见下图),但仍然会在多边形外部结束,因此该方法不会将其检测为交点

Line cuts through polygon

我考虑过传递linestring的先前坐标以生成linestring的一部分,但我不认为Mapbox有一种方法可以检查linestring是否在任何点与polygon相交

如何检查linestring是否与多边形相交


共 (1) 个答案

  1. # 1 楼答案

    首先,您的Point似乎是错误的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));
            }
        }
    }