Javascript 从点查找线段上最近点的坐标

Javascript 从点查找线段上最近点的坐标,javascript,cesium,Javascript,Cesium,我需要计算从点p到线段AB的垂直线的底部。我需要点C的坐标,其中PC是从点p到线段AB的垂直线 我在这方面几乎找不到答案,但向量积过程对我不起作用。 以下是我尝试过的: function nearestPointSegment(a, b, c) { var t = nearestPointGreatCircle(a,b,c); return t; } function nearestPointGreatCircle(a, b, c) { var a_cartesian = n

我需要计算从点p到线段AB的垂直线的底部。我需要点C的坐标,其中PC是从点p到线段AB的垂直线

我在这方面几乎找不到答案,但向量积过程对我不起作用。 以下是我尝试过的:

function nearestPointSegment(a, b, c) {
   var t = nearestPointGreatCircle(a,b,c);
   return t;
}

function nearestPointGreatCircle(a, b, c) {
  var a_cartesian = normalize(Cesium.Cartesian3.fromDegrees(a.x,a.y))
  var b_cartesian = normalize(Cesium.Cartesian3.fromDegrees(b.x,b.y))
  var c_cartesian = normalize(Cesium.Cartesian3.fromDegrees(c.x,c.y))
  var G = vectorProduct(a_cartesian, b_cartesian);
  var F = vectorProduct(c_cartesian, G);
  var t = vectorProduct(G, F);
  t = multiplyByScalar(normalize(t), R);
  return fromCartesianToDegrees(t);
}

function vectorProduct(a, b) {
    var result = new Object();
    result.x = a.y * b.z - a.z * b.y;
    result.y = a.z * b.x - a.x * b.z;
    result.z = a.x * b.y - a.y * b.x;
    return result;
}

function normalize(t) {
    var length = Math.sqrt((t.x * t.x) + (t.y * t.y) + (t.z * t.z));
    var result = new Object();
    result.x = t.x/length;
    result.y = t.y/length;
    result.z = t.z/length;
    return result;
}

function multiplyByScalar(normalize, k) {
    var result = new Object();
    result.x = normalize.x * k;
    result.y = normalize.y * k;
    result.z = normalize.z * k;
    return result;
}

function fromCartesianToDegrees(pos) {
  var carto  = Cesium.Ellipsoid.WGS84.cartesianToCartographic(pos);     
  var lon = Cesium.Math.toDegrees(carto.longitude); 
  var lat = Cesium.Math.toDegrees(carto.latitude); 
  return [lon,lat];
}
我缺少什么?

这里有一个方法:

// edge cases
if (a.x === b.x) {
  // AB is vertical
  c.x = a.x;
  c.y = p.y;
}
else if (a.y === b.y) {
  // AB is horizontal
  c.x = p.x;
  c.y = a.y;
}
else {
  // linear function of AB
  var m1 = (b.y - a.y) / (b.x - a.x);
  var t1 = a.y - m1 * a.x;
  // linear function of PC
  var m2 = -1 / m1; // perpendicular
  var t2 = p.y - m2 * p.x;
  // c.x * m1 + t1 === c.x * m2 + t2
  c.x = (t2 - t1) / (m1 - m2);
  c.y = m1 * c.x + t1;
}
编辑:

这里有一种更好的基于向量的方法:

功能脚(A、B、P){
常数AB={
x:B.x-A.x,
y:B.y-A.y
};
常数k=((P.x-A.x)*AB.x+(P.y-A.y)*AB.y)/(AB.x*AB.x+AB.y*AB.y);
返回{
x:A.x+k*AB.x,
y:A.y+k*AB.y
};
}
常数A={x:1,y:1};
常数B={x:4,y:5};
常数P={x:4.5,y:3};
常数C=英尺(A,B,P);
控制台日志(C);
//垂直的?
常数AB={
x:B.x-A.x,
y:B.y-A.y
};
常数PC={
x:C.x-P.x,
y:C.y-P.y
};
console.log((AB.x*PC.x+AB.y*PC.y).toFixed(3))