2016-11-03 31 views
1

中找到線段上最近點的座標,我需要計算從點P到線段AB繪製的垂直線的英尺。我需要C點垂直於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

這裏有一種方法:

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