gpt4 book ai didi

javascript - 在最接近第三点javascript的线上找到一个点

转载 作者:行者123 更新时间:2023-12-05 05:25:08 26 4
gpt4 key购买 nike

我试图在一条直线上找到离直线第三个点最近的点。这些点是纬度/经度。

简单的图形显示了我正在努力实现的目标。我将它用于 javascript,但任何语言或公式仍然有效。我知道这是基本的几何学,但我仍然无法在 google 上找到公式 :S lol...留在学校!

var a = '48,-90';
var b = '49,-92';
var c = '48.25,-91.8';
var d = 'calculated point on line';

enter image description here

最佳答案

RCrowe @ Find a point in a polyline which is closest to a latlng

/* desc Static function. Find point on lines nearest test point
test point pXy with properties .x and .y
lines defined by array aXys with nodes having properties .x and .y
return is object with .x and .y properties and property i indicating nearest segment in aXys
and property fFrom the fractional distance of the returned point from aXy[i-1]
and property fTo the fractional distance of the returned point from aXy[i] */


function getClosestPointOnLines(pXy, aXys) {

var minDist;
var fTo;
var fFrom;
var x;
var y;
var i;
var dist;

if (aXys.length > 1) {

for (var n = 1 ; n < aXys.length ; n++) {

if (aXys[n].x != aXys[n - 1].x) {
var a = (aXys[n].y - aXys[n - 1].y) / (aXys[n].x - aXys[n - 1].x);
var b = aXys[n].y - a * aXys[n].x;
dist = Math.abs(a * pXy.x + b - pXy.y) / Math.sqrt(a * a + 1);
}
else
dist = Math.abs(pXy.x - aXys[n].x)

// length^2 of line segment
var rl2 = Math.pow(aXys[n].y - aXys[n - 1].y, 2) + Math.pow(aXys[n].x - aXys[n - 1].x, 2);

// distance^2 of pt to end line segment
var ln2 = Math.pow(aXys[n].y - pXy.y, 2) + Math.pow(aXys[n].x - pXy.x, 2);

// distance^2 of pt to begin line segment
var lnm12 = Math.pow(aXys[n - 1].y - pXy.y, 2) + Math.pow(aXys[n - 1].x - pXy.x, 2);

// minimum distance^2 of pt to infinite line
var dist2 = Math.pow(dist, 2);

// calculated length^2 of line segment
var calcrl2 = ln2 - dist2 + lnm12 - dist2;

// redefine minimum distance to line segment (not infinite line) if necessary
if (calcrl2 > rl2)
dist = Math.sqrt(Math.min(ln2, lnm12));

if ((minDist == null) || (minDist > dist)) {
if (calcrl2 > rl2) {
if (lnm12 < ln2) {
fTo = 0;//nearer to previous point
fFrom = 1;
}
else {
fFrom = 0;//nearer to current point
fTo = 1;
}
}
else {
// perpendicular from point intersects line segment
fTo = ((Math.sqrt(lnm12 - dist2)) / Math.sqrt(rl2));
fFrom = ((Math.sqrt(ln2 - dist2)) / Math.sqrt(rl2));
}
minDist = dist;
i = n;
}
}

var dx = aXys[i - 1].x - aXys[i].x;
var dy = aXys[i - 1].y - aXys[i].y;

x = aXys[i - 1].x - (dx * fTo);
y = aXys[i - 1].y - (dy * fTo);

}

return { 'x': x, 'y': y, 'i': i, 'fTo': fTo, 'fFrom': fFrom };
}

关于javascript - 在最接近第三点javascript的线上找到一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32281168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com