Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I was quite unsatisfied with Calculating Length of Linestrings in WGS84 in Miles. It kept me wondering if there is a more convenient, Pythonic way to calculate the length of a WKT linestring according to a given SRID.

I have in mind something like:

srid="WGS84"
line="LINESTRING(3.0 4.0, 3.1 4.1)"
print length(line, srid)

I'm looking for an accurate answer, not sin\cos approximations.

Any ideas?

share|improve this question
    
tomkralidis, this is a GIS website. your answer ignores that the this is a distance between geospatial coordinates (look up SRID). shapely in of itself cannot compute geospatial distances as it has no knowledge of map projection. –  user23037 Oct 18 '13 at 1:32

3 Answers 3

up vote 13 down vote accepted

The geopy module provides the Vincenty formula, which provides accurate ellipsoid distances. Couple this with the wkt loading in Shapely, and you have reasonably simple code:

from geopy import distance
from shapely.wkt import loads

line_wkt="LINESTRING(3.0 4.0, 3.1 4.1)"

# a number of other elipsoids are supported
distance.VincentyDistance.ELLIPSOID = 'WGS-84'
d = distance.distance

line = loads(line_wkt)

# convert the coordinates to xy array elements, compute the distance
dist = d(line.xy[0], line.xy[1])

print dist.meters
share|improve this answer
1  
+1, would have +10 if I could. Saved my team hours of programming. –  Adam Matan Dec 1 '10 at 22:03
    
Is this approach any different from @tomkralidis answer if the input coordinates are in WGS-84 already? –  LarsVegas Dec 18 '13 at 7:54
    
@LarsVegas yes, Shapely only handles planar coordinates -- so it will measure distances accurately in projected space, but not geographic (e.g. WGS-1984). –  scw Dec 23 '13 at 4:05

You could also use Shapely's length property, i.e.:

from shapely.wkt import loads

l=loads('LINESTRING(3.0 4.0, 3.1 4.1)')
print l.length
share|improve this answer

I'd use ogr2ogr (http://www.gdal.org/ogr/index.html) to do it directly but if you really must use python then there are python bindings (http://pypi.python.org/pypi/GDAL/) to let you do it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.