js 求multipolyline 折中点
你可以使用以下代码来找到 multipolyline 的折中点:
function findMidpoint(multipolyline) {
let totalLength = 0;
let lengths = [];
// 计算multipolyline每个线段的长度和总长度
for (let i = 0; i < multipolyline.length; i++) {
let polyline = multipolyline[i];
let length = 0;
for (let j = 1; j < polyline.length; j++) {
let p1 = polyline[j - 1];
let p2 = polyline[j];
length += Math.sqrt(Math.pow(p2[0] - p1[0], 2) + Math.pow(p2[1] - p1[1], 2));
}
totalLength += length;
lengths.push(length);
}
// 找到总长度的一半
let halfLength = totalLength / 2;
let currentLength = 0;
let currentSegment = 0;
// 找到折中点所在的线段和该线段上的位置
for (let i = 0; i < lengths.length; i++) {
currentLength += lengths[i];
if (currentLength > halfLength) {
currentSegment = i;
break;
}
}
// 计算折中点的坐标
let polyline = multipolyline[currentSegment];
let remainingLength = halfLength - (currentLength - lengths[currentSegment]);
let length = 0;
for (let j = 1; j < polyline.length; j++) {
let p1 = polyline[j - 1];
let p2 = polyline[j];
let segmentLength = Math.sqrt(Math.pow(p2[0] - p1[0], 2) + Math.pow(p2[1] - p1[1], 2));
if (length + segmentLength > remainingLength) {
let ratio = (remainingLength - length) / segmentLength;
let x = p1[0] + (p2[0] - p1[0]) * ratio;
let y = p1[1] + (p2[1] - p1[1]) * ratio;
return [x, y];
}
length += segmentLength;
}
return null;
}
这个函数接受一个 multipolyline 参数,其中每个元素都是一个多段折线,每个折线都是由一组点表示的数组。它将返回折中点的坐标。如果无法计算折中点,则返回 null
原文地址: http://www.cveoy.top/t/topic/hv5m 著作权归作者所有。请勿转载和采集!