Openlayers配合Turf.js用EPSG:3857计算两点距离异常及转换报错问询
问题解决方案
1. 坐标转换报错原因
你提交的转换代码中存在投影名称拼写错误:错误拼写为ESPG:4326,正确的投影编码为EPSG:4326,OpenLayers无法识别错误的投影标识,因此抛出destinationProjection is null报错。
2. Turf.js距离计算值过大原因
Turf.js的所有空间运算接口默认接收EPSG:4326(WGS84经纬度)坐标系的坐标值,你直接传入EPSG:3857(Web墨卡托)坐标系的坐标,会被Turf误认为是经纬度数值,最终计算得到的距离结果会严重偏离实际值。
3. 修正后的完整代码
listener.value = sketch.value.getGeometry().on('change', (evt) => { const geom = evt.target; const coordList = geom.getCoordinates()[0]; // 修正投影拼写,将两点坐标转为EPSG:4326格式 const fromCoord = olProj.transform(coordList.slice(-3)[0], 'EPSG:3857', 'EPSG:4326'); const toCoord = olProj.transform(coordList.slice(-2)[0], 'EPSG:3857', 'EPSG:4326'); const from = turf.point(fromCoord); const to = turf.point(toCoord); // Turf.distance默认返回单位为千米,乘以1000可转为米单位 const distance = turf.distance(from, to) * 1000; console.log(distance); });
可选优化方案
如果是小范围场景计算,无需引入Turf.js也可以直接计算:EPSG:3857坐标系本身单位为米,直接计算两点平面距离即可得到近似结果,性能更高:
listener.value = sketch.value.getGeometry().on('change', (evt) => { const geom = evt.target; const coordList = geom.getCoordinates()[0]; const from = coordList.slice(-3)[0]; const to = coordList.slice(-2)[0]; const distance = Math.sqrt(Math.pow(from[0] - to[0], 2) + Math.pow(from[1] - to[1], 2)); console.log(distance); });
内容的提问来源于stack exchange,提问作者Stephen
相关产品推荐
相关产品推荐

