Openlayers - Turf.js 使用 EPSG:3857 获取两点之间的距离

Openlayers - Turf.js Get distance between two Points using EPSG:3857

我想向用户显示从最后绘制的点到光标的距离。为此,我需要为要素的几何形状添加一个更改侦听器。

每次用户移动鼠标时都会触发此更改,我需要计算距离。所以为了这样做,我想使用 Turf.js。但问题是输出距离太大了。我觉得和我用的坐标系有关。

在我的项目中,我的坐标在 EPSG:3857 中,我认为距离函数需要 ESPG:4326。我曾尝试使用 ol proj 进行转换。但随后我收到一条错误消息:Uncaught TypeError: destinationProjection is null

olProj.transform(geom.getCoordinates()[0].slice(-3)[0], 'EPSG:3857', 'ESPG:4326');

      listener.value = sketch.value.getGeometry().on('change', (evt) => {
        const geom = evt.target;

        var from = turf.point(geom.getCoordinates()[0].slice(-3)[0]);
        var to = turf.point(geom.getCoordinates()[0].slice(-2)[0]);
        console.log(turf.distance(from, to));
      });

它是空的,因为 'ESPG:4326' 应该是 'EPSG:4326'。但你不需要地盘来做到这一点

new ol.geom.LineString(geom.getCoordinates()[0].slice(-3, -1)).getLength()

将以投影单位给出段的长度,或者

ol.sphere.getLength(new ol.geom.LineString(geom.getCoordinates()[0].slice(-3, -1)))

将给出段的半正弦长度