首页 > 解决方案 > 如何检查线串是否与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与多边形相交?

标签: javamapboxpolygonintersection

解决方案


首先,您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));
        }
    }
}

推荐阅读