需求:需要对距离橙色点位最近的线的做垂直箭头
1.使用for循环遍历直线列表,使用getPointToLineDistance方法获取点到线的距离,生成一个包含线坐标和点位距离的新点位列表。
// 包含距离的列表
let newPoints = [];
for (let i = 0; i < points.length; i++) {
// 判断是否为最后一个点位
if (points[i + 1]) {
// 获取当前点位
const now = points[i];
// 获取下一个点位
const next = points[i + 1];
const list = [[now.lng, now.lat], [next.lng, next.lat]]
// 获取点到线之间的距离
const distance = this.getPointToLineDistance(list, point)
newPoints.push({
now,
next,
distance
})
}
}
2.使用sort函数对新点位列表进行排序,取列表中第一个对象作为参数使用getVerticalPoint方法获取线上与点位垂直的坐标,传入点位坐标和垂直坐标生成垂直箭头线
// 对点位根据距离进行升序排序
newPoints = newPoints.sort((a, b) => a.distance - b.distance);
// 获取距离最短的点位对象
const { now, next } = newPoints[0];
const list = [[now.lng, now.lat], [next.lng, next.lat]]
const vertical = this.getVerticalPoint(list, point)
// 箭头点位列表
let arrowPoints = [];
arrowPoints.push(new T.LngLat(point[0], point[1]));
arrowPoints.push(new T.LngLat(vertical.x, vertical.y));
let vline = new T.PolylineArrow(arrowPoints, {
weight: 4,
lineStyle: 'dashed',
color: '#0079fe',
opacity: 1
});
this.map.addOverLay(vline);
完整代码:
/**
* @param {*} points 点位列表
* @param {*} point 点的坐标
*/
initArrowLine(points, point) {
// 包含距离的列表
let newPoints = [];
// 箭头点位列表
let arrowPoints = [];
for (let i = 0; i < points.length; i++) {
// 判断是否为最后一个点位
if (points[i + 1]) {
// 获取当前点位
const now = points[i];
// 获取下一个点位
const next = points[i + 1];
const list = [[now.lng, now.lat], [next.lng, next.lat]]
// 获取点到线之间的距离
const distance = this.getPointToLineDistance(list, point)
newPoints.push({
now,
next,
distance
})
}
}
// 对点位根据距离进行升序排序
newPoints = newPoints.sort((a, b) => a.distance - b.distance);
// 获取距离最短的点位对象
const { now, next } = newPoints[0];
const list = [[now.lng, now.lat], [next.lng, next.lat]]
const vertical = this.getVerticalPoint(list, point)
arrowPoints.push(new T.LngLat(point[0], point[1]));
arrowPoints.push(new T.LngLat(vertical.x, vertical.y));
let vline = new T.PolylineArrow(arrowPoints, {
weight: 4,
lineStyle: 'dashed',
color: '#0079fe',
opacity: 1
});
this.map.addOverLay(vline);
},
效果图:
点到直线方程求出点到直线的距离
// 获取点到直线的距离
getPointToLineDistance(list, point) {
let [[x1, y1], [x2, y2]] = list;
let [x, y] = point;
if (x1 === x2) {
return Math.abs(x - x1);
} else if (y1 === y2) {
return Math.abs(y - y1);
}
// return Math.abs((y1 - y2) * x + (x2 - x1) * y + x1 * y2 - y1 * x2)
return Math.abs((y1 - y2) * x + (x2 - x1) * y + (y2 - y1) * x1 + (x1 - x2) * y1)
/
Math.sqrt((y1 - y2) * (y1 - y2) + (x1 - x2) * (x1 - x2));
},
原文章地址为:js点到两点确定的直线最短距离(点到直线方程)-CSDN博客
获取点到线垂直坐标
// 获取垂直点位
getVerticalPoint(list, point) {
let [[x1, y1], [x2, y2]] = list;
let [x, y] = point;
const dx = x1 - x2
const dy = y1 - y2
const EPS = 0.00000001
// 确保两个点不是同一个点
if (Math.abs(dx) < EPS &&
Math.abs(dy) < EPS) {
return begin
}
//计算斜率
let u = (x - x1) * (x1 - x2) +
(y - y1) * (y1 - y2)
u = u / (Math.pow(dx, 2) + Math.pow(dy, 2))
return {
x: x1 + u * dx,
y: y1 + u * dy
}
},