Search code examples
openlayersturfjsproj4js

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


I want to show the user the distance from the last drawn point to the cursor. In order to do so I need to add a change listener to the geometry of the feature.

Every time the user moves the mouse this change will get triggered and I need to calculate the distance. So in order to do so I want to use Turf.js. But the problem is that output distance is way to big. I think it has to do with the coordinate system I use.

In my project I the coordinates are in EPSG:3857 and I think the distance function expects ESPG:4326. I have tried to use ol proj in order to convert. But then I get an error stating: 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));
      });

Solution

  • It is null because 'ESPG:4326' should be 'EPSG:4326'. But you do not need turf to do that

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

    will give length of the segment in projection units, or

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

    will give haversine length of the segment