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

时间:2016-11-03 12:51:21

标签: javascript cesium

我需要计算从点P到线段AB的垂直线的脚。我需要点C的坐标,其中PC从点P垂直绘制到线AB。

enter image description here

我在SO here上找不到答案,但矢量产品流程对我不起作用。 这是我试过的:

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

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

这是一种方式:

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