3

I'm new to qgis and I want to find the length of some roads in a map. So I used the following code,

from shapely.wkb import loads

def getLength():

layer = qgis.utils.iface.mapCanvas().currentLayer()
total = 0
for feature in layer.selectedFeatures():
    geom = feature.geometry()
    wkb = geom.asWkb()
    line = loads(wkb)
    total = total + line.length
return total

print getLength()

It shows the length in degrees I think. Is there any way to convert the result I got to meters, without changing the CRS of project. I want to do it programatically(without adding new field using field calculator).

6
  • You know QgsGeometry has a length() method you can use rather then using shapely.
    – Nathan W
    Commented Oct 26, 2014 at 12:13
  • Yes sir. I saw that code of you too. But is there any way I can convert the result I got to meters, a formula or something?
    – Dil
    Commented Oct 26, 2014 at 12:16
  • Related (duplicate?): gis.stackexchange.com/questions/26335/…
    – Chris W
    Commented Oct 26, 2014 at 22:00
  • So what do I get as the answer, is it latitude? I'm very sorry if this is stupid question.. Please help me to clarify..
    – Dil
    Commented Oct 28, 2014 at 12:57
  • As one of the comments in the question I linked to points out (and is discussed at other questions), there is no direct conversion between meters and degrees because the length of a degree of longitude (an angular measurement) varies depending on the latitude. Depending on your accuracy requirements and distances covered, you could make a fixed assumption. See gis.stackexchange.com/questions/2951/…
    – Chris W
    Commented Oct 31, 2014 at 20:33

1 Answer 1

1

One option would be to use the processing qgis:reprojectlayer to reproject the selected features and save them to an in memory layer. Once you have this layer then use the QgsGeometry length() method noted by Nathan W to get the feature length in meters.

# make sure you have selected features first
import processing
result = processing.runalg('qgis:reprojectlayer', layer, "EPSG:102013", None) # change EPSG value to desired CRS
inMemoryLayer = processing.getObject(result['OUTPUT'])
# continue on and get feature geometry length...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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