[GIS] Distance Between Two Points vs Length of Linestring

distancelengthlinestringpostgis

So I have two points that I want to calculate the distance between. If I use:

SELECT
  ST_Distance_Spheroid(point_a, point_b, 'SPHEROID["GRS 1980",6378137,298.257222101]') / 1000
FROM (
       VALUES (
         ST_GeomFromText('POINT(116.330533333333 39.976266666667)'),
         ST_GeomFromText('POINT(116.34415 39.97875)')
       )
     ) AS query (point_a, point_b);

I get the value 1.1953967900687876km. I think this is the correct value since when I use any online distance calculator I get this result; however, if I put the two points into a LINESTRING and then compute the length I get a different number:

SELECT
  ST_Length2D_Spheroid(trajectory, 'SPHEROID["GRS 1980",6378137,298.257222101]') / 1000
FROM (
       VALUES (
         ST_GeomFromEWKT('SRID=4326;LINESTRING(39.976266666667 116.330533333333, 39.97875 116.34415)')
       )) AS query(trajectory);

I get the value 1.5228519672706637km. I don't understand why this is happening. In the case of just two points shouldn't these distance bet the same?

Thanks in advance.

Best Answer

There actually is no difference between the two functions, which both yield 1.195 km. The problem is that in your question the axis order is flipped for trajectory, so you are seeing different answers than you expect.

SELECT
  ST_AsLatLonText(point_a) AS point_a_latlon,
  ST_AsLatLonText(point_b) AS point_b_latlon,
  ST_Distance_Spheroid(point_a, point_b, spheroid) / 1000 AS ST_Distance_Spheroid_km,
  ST_Length2D_Spheroid(ST_MakeLine(point_a, point_b), spheroid) / 1000 AS ST_Length2D_Spheroid_km
FROM (SELECT
  ST_GeomFromText('POINT(116.330533333333 39.976266666667)', 4326) AS point_a,
  ST_GeomFromText('POINT(116.34415 39.97875)', 4326) AS point_b,
  'SPHEROID["GRS 1980",6378137,298.257222101]'::spheroid
) AS f;
-[ RECORD 1 ]-----------+-------------------------------
point_a_latlon          | 39°58'34.560"N 116°19'49.920"E
point_b_latlon          | 39°58'43.500"N 116°20'38.940"E
st_distance_spheroid_km | 1.19539679006871
st_length2d_spheroid_km | 1.19539679006871