我有两个 GPS 坐标,它们连接在一起形成一条线。我还有一个 GPS 点,它靠近但从未完全在线上。我的问题是,如何找到沿线到给定点最近的点?
最佳答案
Game Dev has an answer to this ,它在 C++ 中,但应该很容易移植。哪个CarlG有kindly 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/