Search code examples
google-mapsgoogle-maps-api-3haversineturfjs

Why turfjs distance returns results different from Google Map geometry libs computeDistanceBetween?


I am puzzled on why the two libraries provide different results.

const CATA = {
  lat: 57.312004,
  lng: 25.289825
};

const PK = {
  lat: 57.307953,
  lng: 25.295025
};

const tCATA = turf.point([CATA.lat, CATA.lng]);
const tPK = turf.point([PK.lat, PK.lng]);
const tDistance = turf.distance(tCATA, tPK, { units: "meters" });

const gCATA = new google.maps.LatLng(CATA);
const gPK = new google.maps.LatLng(PK);
const gDistance = google.maps.geometry.spherical.computeDistanceBetween(
  gCATA,
  gPK
);

console.log(tDistance, gDistance); // 707.249063108749, 548.7294775022126

CodeSandbox: https://codesandbox.io/s/boring-hawking-b7uwh

Okay, one thing might be that turfjs uses different radius for Earth (6371008.8) than Google (6378137). But even providing turfs radius for the computeDistanceBetween, the results still differ for ~150 meters.

But, assuming that computeDistanceBetween respects the radius parameter, I assume Google relies on Haversine too, like turf does...


Solution

  • Both functions actually return the same values, when used properly!

    Apparently, turfjs - since it is based on GeoJSON - uses LngLat formation instead of LatLng. Switching them around in turf.point definitions resolves the question and fixes all the related stuff I had.

    For reference: https://macwright.org/lonlat/

    A frustrating inconsistency in geospatial (mapping) software is coordinate order. Coordinates are often represented as arrays, like [-87.73, 41.83], instead of objects, like { lng: -87.73, lat: 41.83 }. This leaves it up to the developer to determine whether -87.73 is the longitude or latitude. One choice places a point on Chicago, and the other a location deep in Antarctica.

    There's some consensus growing around longitude, latitude order for geospatial formats, but still chaos for libraries and software. It's up to the developer to be aware of this issue and read the requisite documentation, and flip coordinates if necessary to translate between different systems.