Turf.js – How to Correct Length Calculation Errors

turf

I'm trying to calculate the distance between 2 points given by GPS coordinates using the turf.js library. My code looks like this:

const s1 = {
    lat: 48.60538779779193,
    lng: 18.887075288025212
}

const s2 = {
    lat: 48.60544807307272,
    lng: 18.887834925208427
}

const lineString = turf.lineString([[s1.lat, s1.lng], [s2.lat, s2.lng]]);
const lLength = turf.length(lineString, {units: "meters"});
console.log(lLength);

This yields an incorrect result of 84.705625m

I tried calculate it using this site – https://www.fcc.gov/media/radio/distance-and-azimuths

This one gives a correct result:
enter image description here

Also measuring the 2 points in QGIS shows a distance of 56.4m

What's the catch here? Is turf.js buggy or am I missing something?

Best Answer

Your mistake is in wrong order of coordinates. turf.js requires [lng, lat] order (see for example http://turfjs.org/docs/#point).

So if you calculate like this

const lineString = turf.lineString([[s1.lng, s1.lat], [s2.lng, s2.lat]]);
const lLength = turf.length(lineString, {units: "meters"});

, you'll get:

56.254338683733785