20

In PostGIS, the ST_length() function returns the length of a LineString in some units, but not in meters.

Is there a function like ST_Length() but in meters?

Taras
  • 32,823
  • 4
  • 66
  • 137
José Alejandro
  • 591
  • 1
  • 4
  • 11

4 Answers4

28

It looks like since PostGIS 2.0 (maybe before) you can also just do this with ST_Length by recasting the geometry to geography:

ST_Length(geom::geography)

For example, the distance between 50°N, 12°E and 51°N, 13°E:

SELECT ST_Length(geom) AS deg,
       ST_Length(geom::geography)/1000 AS km_1,
       ST_LengthSpheroid(geom, 'SPHEROID["WGS 84",6378137,298.257223563]')/1000 as km_2
FROM   ST_GeomFromText('LINESTRING(12 50, 13 51)' , 4326) AS geom

which gives

       deg       |       km_1       |       km_2       
-----------------+------------------+------------------
 1.4142135623731 | 131.935962780384 | 131.935962780384
andybega
  • 527
  • 1
  • 4
  • 11
  • 1
    In PostGIS, this is now ST_LengthSpheroid not ST_Length_Spheroid; see: https://postgis.net/docs/ST_Length_Spheroid.html – fooquency Feb 20 '22 at 17:01
12

St_Length() returns the length in the units of its Spatial Reference System. If you want to get meters, you will need to transform your feature to a different SRS that uses meters as units. This can be done on-the-fly, so don't worry about writing out another data set.

SELECT ST_AsText(ST_Transform(the_geom,26915)) from my_table;

In this example, SRID 26915 is UTM Zone 15 N, NAD83.

DavidF
  • 4,862
  • 1
  • 26
  • 32
  • Or simply add your own field and manage the calculation yourself. NOTE you have to write your own trigger or recalculate it on changes in your lengths. – Brad Nesom Oct 11 '12 at 04:12
3

Examples of SQL request: how-to-calculate-length-of-polyline-geometry-for-several-tables-in-postgis

SQL request (length in km (/1000 -delete for meters)):

SELECT 
sum(ST_Length_Spheroid(the_geom,'SPHEROID["WGS 84",6378137,298.257223563]'))/1000 AS km_roads 
FROM 
"D1_r";
spatialhast
  • 3,631
  • 2
  • 27
  • 52
0

Use the following formula :

select ST_Length(ST_Transform(ST_GeomFromEWKT('SRID=4326;'||st_astext(the_geom)),26986)) as geolength from my_table;
Kantan
  • 1,917
  • 2
  • 14
  • 26
Loni
  • 1