【问题标题】:Snap point to a line将点捕捉到一条线
【发布时间】:2009-09-22 10:49:36
【问题描述】:

我有两个 GPS 坐标,它们连接在一起形成一条线。我还有一个 GPS 点,它靠近但从不完全在这条线上。我的问题是,我如何找到离给定点最近的点?

【问题讨论】:

  • 请注意,为了绝对精确,您必须考虑测地线距离,这意味着当两个任意点远离赤道时,它们之间存在某种“螺旋”线。但是让我们假设这些点彼此相距很远,或者是吗? ;oP

标签: java line point


【解决方案1】:

Game Dev has an answer to this,它在 C++ 中,但应该很容易移植。其中CarlGkindly done(希望他不介意我转发):

public static Point2D nearestPointOnLine(double ax, double ay, double bx, double by, double px, double py,
        boolean clampToSegment, Point2D dest) {
    // Thanks StackOverflow!
    // https://stackoverflow.com/questions/1459368/snap-point-to-a-line-java
    if (dest == null) {
        dest = new Point2D.Double();
    }

    double apx = px - ax;
    double apy = py - ay;
    double abx = bx - ax;
    double aby = by - ay;

    double ab2 = abx * abx + aby * aby;
    double ap_ab = apx * abx + apy * aby;
    double t = ap_ab / ab2;
    if (clampToSegment) {
        if (t < 0) {
            t = 0;
        } else if (t > 1) {
            t = 1;
        }
    }
    dest.setLocation(ax + abx * t, ay + aby * t);
    return dest;
}

【讨论】:

【解决方案2】:

试试这个:

ratio = (((x1-x0)^2+(y1-y0)^2)*((x2-x1)^2 + (y2-y1)^2) - ((x2-x1)(y1-y0) - (x1-x0)(y2-y1))^2)^0.5
        -----------------------------------------------------------------------------------------
                                            ((x2-x1)^2 + (y2-y1)^2)

xc = x1 + (x2-x1)*ratio;
yc = y1 + (y2-y1)*ratio;

Where:
    x1,y1 = point#1 on the line
    x2,y2 = point#2 on the line
    x0,y0 = Another point near the line
    xc,yx = The nearest point of x0,y0 on the line
    ratio = is the ratio of distance of x1,y1 to xc,yc and distance of x1,y1 to x2,y2
    ^2    = square
    ^0.5  = square root

公式是在我们找到点 x0,y0 到线 (x1,y1 -> x2,y3) 的距离后得出的。 见here

我在这里测试过这段代码(我在上面给你的这个特定的),但我几年前用过类似的方法,它可以工作,所以你可以试试。

【讨论】:

  • 这似乎只适用于线段上的点,而不是穿过这两个点的整条线
【解决方案3】:

您可以为此使用JTS

非常简单的代码示例:

// create Line: P1(0,0) - P2(0,10)
LineSegment ls = new LineSegment(0, 0, 0, 10);
// create Point: P3(5,5)
Coordinate c = new Coordinate(5, 5);
// create snapped Point: P4(0,5)
Coordinate snappedPoint = ls.closestPoint(c);

【讨论】:

    猜你喜欢
    • 2010-09-28
    • 1970-01-01
    • 2018-12-19
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    相关资源
    最近更新 更多