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

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Dil
  • 143
  • 1
  • 12
  • 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?): http://gis.stackexchange.com/questions/26335/how-much-is-1-meter-in-decimal-degrees – 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 http://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters – Chris W Oct 31 '14 at 20:33
  • I multiplied the answers I got from above function by 111,111 and I compared them with the values I got from field calculator($length)(adding another column to attribute table by changing the map units to meters). They are difference from very few meters.(4-5m) – Dil Nov 01 '14 at 15:07

1 Answers1

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...
artwork21
  • 35,114
  • 8
  • 66
  • 134