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).

  • You know QgsGeometry has a length() method you can use rather then using shapely. – Nathan W Oct 26 '14 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 Oct 26 '14 at 12:16
  • Related (duplicate?): gis.stackexchange.com/questions/26335/… – Chris W Oct 26 '14 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 Oct 28 '14 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 Oct 31 '14 at 20:33

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...
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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