Search code examples
openlayers

OpenLayers Caculate distance between two coordinates gives wrong answer


I have a GPX file and I am trying to calculate the total distance between two points with the following function

import { LineString } from 'ol/geom'

getDistance(previous, next){
   const coords = [ previous, next ]
   const line = new LineString(coords);
   return line.getLength();
},

I know getLength() is supposed to return in meters but I am getting some very small numbers and when I add all distances I am nowhere near the 2.6km of the gpx file.

my data looks like this : [[0.194655, 38.730435], [0.194435, 38.730522]] and the distance I am getting for this is 0.0002365776828023007


Solution

  • The output seems correct to me, it's the length of the linestring in degrees.

    To get the distance in meter, try getDistance of ol.Sphere

    https://openlayers.org/en/latest/apidoc/module-ol_sphere.html#.getDistance

    edit: you are confusing the getLength method of LineString with the getLength method of ol.sphere