捕捉指向一条线 [英] Snap point to a line
本文介绍了捕捉指向一条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个GPS坐标连接在一起形成一条线。我还有一个GPS点,它靠近线路,但从未完全在线路上。我的问题是,如何找到沿给定点的最近点?
I have two GPS coordinates which link together to make a line. I also have a GPS point which is near to, but never exactly on, the line. My question is, how do I find the nearest point along the line to the given point?
推荐答案
Game Dev有一个答案,它是在C ++中但它应该很容易移植。哪个 CarlG 完成(希望他不介意我重新发布):
Game Dev has an answer to this, it is in C++ but it should be easy to port over. Which CarlG has kindly done (hopefully he does not mind me reposting):
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;
}
这篇关于捕捉指向一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文