OpenLayers 4如何获取包含海拔的LineString轨迹线长度?
计算OpenLayers 4中带海拔的LineString轨迹长度
嘿,我来帮你搞定这个问题!OpenLayers 4原生的getLength()方法只能计算平面距离,不会考虑坐标里的海拔(Z值),所以我们得手动实现3D长度的计算逻辑——遍历轨迹的每一对相邻点,结合平面距离和海拔差算出每段的实际长度,最后累加得到总长度。
实现步骤与代码
根据你的坐标投影类型,选择对应的计算方式:
情况1:坐标是WGS84经纬度(EPSG:4326)
这种情况用球面大圆距离计算平面部分,更贴合地球曲面的实际:
function calculate3DLineLength(lineString) { const coordinates = lineString.getCoordinates(); let totalLength = 0; // 点数量不足2时直接返回0 if (coordinates.length < 2) return totalLength; for (let i = 0; i < coordinates.length - 1; i++) { const [lon1, lat1, z1] = coordinates[i]; const [lon2, lat2, z2] = coordinates[i + 1]; // 检查是否存在海拔值 if (z1 === undefined || z2 === undefined) { console.warn(`第${i+1}段轨迹缺少海拔信息,将仅计算平面距离`); // 回退到平面大圆距离计算 totalLength += ol.sphere.getDistance([lon1, lat1], [lon2, lat2]); continue; } // 计算两点间的球面大圆距离(单位:米) const planarDistance = ol.sphere.getDistance([lon1, lat1], [lon2, lat2]); // 计算海拔差 const elevationDiff = z2 - z1; // 用勾股定理计算这段轨迹的3D长度 const segmentLength = Math.sqrt(Math.pow(planarDistance, 2) + Math.pow(elevationDiff, 2)); totalLength += segmentLength; } return totalLength; }
情况2:坐标是平面投影(如EPSG:3857、UTM等)
如果坐标已经转换为米为单位的平面投影,直接用平面坐标距离计算即可:
function calculate3DLineLength(lineString) { const coordinates = lineString.getCoordinates(); let totalLength = 0; if (coordinates.length < 2) return totalLength; for (let i = 0; i < coordinates.length - 1; i++) { const [x1, y1, z1] = coordinates[i]; const [x2, y2, z2] = coordinates[i + 1]; if (z1 === undefined || z2 === undefined) { console.warn(`第${i+1}段轨迹缺少海拔信息,将仅计算平面距离`); totalLength += ol.coordinate.distance([x1, y1], [x2, y2]); continue; } // 计算平面坐标距离(单位:米) const planarDistance = ol.coordinate.distance([x1, y1], [x2, y2]); const elevationDiff = z2 - z1; const segmentLength = Math.sqrt(Math.pow(planarDistance, 2) + Math.pow(elevationDiff, 2)); totalLength += segmentLength; } return totalLength; }
如何使用
在你创建完trackline之后,直接调用这个函数就能得到带海拔的轨迹长度:
var trackline = new ol.geom.LineString(points); // points为包含海拔的坐标数组,格式如[lon, lat, z]或[x, y, z] var featurething = new ol.Feature({geometry: trackline}); // ... 你的样式设置代码 ... // 计算并输出3D长度 var track3DLength = calculate3DLineLength(trackline); console.log(`轨迹线的3D总长度(米):${track3DLength}`);
小提示
- 函数会自动处理缺少海拔的点,回退到平面距离计算并给出警告。
- 计算结果的单位是米,和OpenLayers原生距离方法的单位一致。
内容的提问来源于stack exchange,提问作者Tommiee
相关产品推荐
相关产品推荐

