Trilateration(三邊測量)是一種常用的定位算法
已知三點位置 (x1, y1), (x2, y2), (x3, y3)
已知未知點 (x0, y0) 到三點距離 d1, d2, d3
以 d1, d2, d3 為半徑作三個圓,根據畢達哥拉斯定理,得出交點即未知點的位置計算公式:
( x1 - x0 )2 + ( y1 - y0 )2 = d12
( x2 - x0 )2 + ( y2 - y0 )2 = d22
( x3 - x0 )2 + ( y3 - y0 )2 = d32

設未知點位置為 (x, y), 令其中的第一個球形 P1 的球心坐標為 (0, 0),P2 處於相同縱坐標,球心坐標為 (d, 0),P3 球心坐標為 (i, j),三個球形半徑分別為 r1, r2, r3,z為三球形相交點與水平面高度。則有:
r12 = x2 + y2 + z2
r22 = (x - d)2 + y2 + z2
r32 = (x - i)2 + (y - j)2 + z2
當 z = 0 時, 即為三個圓在水平面上相交為一點,首先解出 x:
x = (r12 - r22 + d2) / 2d
將公式二變形,將公式一的 z2 代入公式二,再代入公式三得到 y 的計算公式:
y = (r12 - r32 - x2 + (x - i)2 + j2) / 2j
JAVA算法實現
public class Algorithem {
public static void main(String[] args){
double[] xy = Algorithem.trilateration(12641371.971, 4138703.5211, 6, 12641381.9026, 4138706.4714, 6, 12641370.7839, 4138708.7705, 6);
System.out.println(xy[0]+"::"+xy[1]);
}
public static double[] trilateration(double x1,double y1,double d1, double x2, double y2,double d2, double x3, double y3, double d3)
{
double []d={0.0,0.0};
double a11 = 2*(x1-x3);
double a12 = 2*(y1-y3);
double b1 = Math.pow(x1,2)-Math.pow(x3,2) +Math.pow(y1,2)-Math.pow(y3,2) +Math.pow(d3,2)-Math.pow(d1,2);
double a21 = 2*(x2-x3);
double a22 = 2*(y2-y3);
double b2 = Math.pow(x2,2)-Math.pow(x3,2) +Math.pow(y2,2)-Math.pow(y3,2) +Math.pow(d3,2)-Math.pow(d2,2);
d[0]=(b1*a22-a12*b2)/(a11*a22-a12*a21);
d[1]=(a11*b2-b1*a21)/(a11*a22-a12*a21);
return d;
}
}
D3.js實現
定義三個圓的坐標及半徑,計算出交點的坐標 (obj_x, obj_y).
var x_0 = 150, y_0 = 150;
var x_1 = x_0, y_1 = y_0, d = 150, x_2 = x_0 + d, x_3 = 225, y_3 = 315, r = 100;
var i = x_3 - x_0, j = y_3 - y_0;
var x = (Math.pow(r, 2) - Math.pow(r, 2) + Math.pow(d, 2)) / (2 * d) + x_0;
var obj_x = x + x_0;
var y = (Math.pow(r, 2) - Math.pow(r, 2) - Math.pow(x, 2) + Math.pow((x - i), 2)
+ Math.pow(j, 2)) / (2 * j);
var obj_y = y + y_0;
繪出圓形及交點:
svg.append("circle").attr("cx", x_1)
.attr("cy", y_1).attr("r", r)
.style("fill", "blue").style("opacity", 0.3);
svg.append("circle").attr("cx", x_2)
.attr("cy", y_0).attr("r", r)
.style("fill", "red").style("opacity", 0.4);
svg.append("circle").attr("cx", x_3)
.attr("cy", y_3).style("opacity", 0.5)
.attr("r", r).style("fill", "yellow");
svg.append("circle").attr("cx", obj_x)
.attr("cy", obj_y).attr("r", 3)
.style("fill", "red");
