捕捉指向一条线

3 java point line

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

Mic*_*mlk 11

游戏开发有一个答案,它是在C++中,但它应该很容易移植.这CarlG好心做了(希望他不介意我重新发布):

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 该算法对我来说正常工作 - 这里移植到Java:http://pastebin.com/n9rUuGRh (3认同)