(取自定位导航项目)
哇!这不就是一道初中的数学题嘛!But...
已知三点 A(m,n),B(P,q),C(s,f),并且坐标都是已知的。
通过直线方程 y=kx+b及A、B两点,可求得直线AB的直线方程中的斜率K及b。
则直线方程已知,通过两点间距离公式,可以求得线段AC的长度。
下面是手写过程:是不是很生动形象
//直线方程 //起点 Point beginPoint = new Point(100,348); //终点 Point overPoint = new Point(662,1067); // 第一步:求得直线方程相关参数y=kx+b // 坐标直线斜率k double k = (overPoint.y - beginPoint.y)*1.0/(overPoint.x - beginPoint.x); // 坐标直线b //最终直线方程 y=1.2605633802816902x+221.94366197183098 double b = beginPoint.y - k * beginPoint.x;
// 两点的坐标距离(走的一段路的距离) double lineDis = Math.sqrt(Math.pow(locX - nextX, 2)*1.0 + Math.pow(locY - nextY, 2)); //将直线公式与坐标距离公式求解方程组,得出在线上距离相同的坐标点 double A = Math.pow(k, 2) + 1;// A=k^2+1; double B = -2 * ((locY -b ) * k + locX);// B=2[(b-y0)k-x0]; // C=(b-y0)^2+x0^2-L^2 double C = Math.pow(locY - b, 2) + Math.pow(locX, 2) - Math.pow(lineDis, 2); // 两根x1,x2= [-B±√(B^2-4AC)]/2A double x1 = (-B + Math.sqrt(Math.pow(B, 2) - 4 * A * C)) / (2 * A); double x2 = (-B - Math.sqrt(Math.pow(B, 2) - 4 * A * C)) / (2 * A);
private void pointXY() { Point curPoint = new Point(20, 30);// 当前坐标 Point nextPoint = new Point(35, 42);// 下个点坐标 double distance = Math.sqrt(Math.pow(curPoint.x - nextPoint.x, 2) + Math.pow(curPoint.y - nextPoint.y, 2));// 两点的坐标距离 double lenthUnit = distance / 5;// 单位长度 // 第一步:求得直线方程相关参数y=kx+b double k = (curPoint.y - nextPoint.y) * 1.0 / (curPoint.x - nextPoint.x);// 坐标直线斜率k double b = curPoint.y - k * curPoint.x;// 坐标直线b // 第二步:求得在直线y=kx+b上,距离当前坐标距离为L的某点 double A = Math.pow(k, 2) + 1;// A=k^2+1; double B = 2 * ((b - curPoint.y) * k - curPoint.x);// B=2[(b-y0)k-x0]; double L =lenthUnit; // C=(b-y0)^2+x0^2-L^2 double C = Math.pow(b - curPoint.y, 2) + Math.pow(curPoint.x, 2) - Math.pow(L, 2); // 两根x1,x2= [-B±√(B^2-4AC)]/2A double x1 = (-B + Math.sqrt(Math.pow(B, 2) - 4 * A * C)) / (2 * A); double x2 = (-B - Math.sqrt(Math.pow(B, 2) - 4 * A * C)) / (2 * A); double x = 0;// 最后确定是在已知两点之间的某点 if (x1 == x2) { x = x1; } else if (curPoint.x <= x1 && x1 <= nextPoint.x || nextPoint.x <= x1 && x1 <= curPoint.x) { x = x1; } else if (curPoint.x <= x2 && x2 <= nextPoint.x || nextPoint.x <= x2 && x2 <= curPoint.x) { x = x2; } double y = k * x + b; Point mPoint = new Point((int) x, (int) y); }