思路是
1/找到一组点中距离最远的两个点,将其中一个作为线的起点
2/为起点找到距离其最近的点,作为线段的第二个点;
3/以第二个点为基准,找距离其最近的点作为第三个点,
4/以此类推,将一组点调整为一条没有重复方向的线
参数为一个二维数组,进入函数为sortLine
// 传入一对数组,传出一个距离值 function distance(pointArr1, pointArr2) { const point1 = turf.point(pointArr1) const point2 = turf.point(pointArr2) return turf.distance(point1, point2) } // 找到离某点最近的点 // 传入一个点和一个数组 // 传出一个点 function findNearestPoint(currentPoint, remainingPoints) { let neareatPoint = null let nearestDistance = Infinity remainingPoints.forEach(point => { const distanceValue = distance(point, currentPoint) if (distanceValue < nearestDistance) { nearestDistance = distanceValue neareatPoint = point } }) return neareatPoint } // 找到一组点当中最远的一组点,用来做有向线的起点 // 传入一组数组,传出一对数组 function findFurthestPoints(points) { let maxDistance = 0 let furthestPair = [] for (let i = 0; i < points.length - 1; i++) for (let j = i + 1; j < points.length; j++) { const distanceValue = distance(points[i], points[j]) if (distanceValue > maxDistance) { maxDistance = distanceValue furthestPair = [points[i], points[j]] } } return furthestPair } export function sortLine(points) { const sortedPoints = [] let currentPoint = findFurthestPoints(points)[0] sortedPoints.push([...currentPoint]) let remainingPoints = [...points].filter(item => (item[0] !== currentPoint[0] || item[1] !== currentPoint[1])) while (remainingPoints.length > 0) { const nearestPoint = findNearestPoint(currentPoint, remainingPoints) sortedPoints.push([...nearestPoint]) currentPoint = nearestPoint remainingPoints = remainingPoints.filter(item => (item[0] !== nearestPoint[0] || item[1] !== nearestPoint[1])) } return sortedPoints }
标签:顺序排列,const,js,item,points,let,currentPoint,turf,remainingPoints From: https://www.cnblogs.com/guoguocode/p/18309773