java - 捕捉点到一条线

标签 java line point

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

最佳答案

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;
}

关于java - 捕捉点到一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1459368/

相关文章:

java - 春袋鼠 : Trigger Action on Update – Best Practice

java - 将历史记录存储在数据库中

c# - 相当于c#中的Point和Size

java - 促进Java应用程序中的SQL表查询功能

java - 如何在正确的项目中加载多项目中的资源路径?

php - 在递增时在同一输出行上回显整数?

c - 使用 c 替换文本中的 2 行而不是 1 行

date - NVD3 线加条形图 X 轴刻度错误对齐

java - .get(key) 不会给我 Hashmap<Point, Integer> 中的值

image - OpenGL:渲染图像 3D 点云