3

I can get what I want by using this code but have to do it everytime i select. The geometry of the features are small (city scale).

layer = qgis.utils.iface.activeLayer()
features = layer.selectedFeatures()
for f in features:
    geom = f.geometry()
    #print "length is ", geom.length()
    #print "area is ", geom.area()

Code taken from here -

Calculate line lengths with Python in QGIS

2 Answers 2

5

You could also try using the inbuilt "identify" tool and clicking on the features. The identify tool will show the feature's geometry information such as length and area under the "derived attributes" group.

1
  • Cheers for the tip!!
    – user35594
    Commented Sep 20, 2016 at 20:25
4

You can use the following code which connects the selectionChanged event (changing features in a layer) to a function. This function will only be applied to line and polygon type shapefiles already loaded into QGIS.

We can also make it so that the sum of the length and area of the selected features is calculated and printed instead of printing out separate values for each feature. Copy/paste the following into the Python Console then click a layer and select your features:

def calc_Geom():
    layer = qgis.utils.iface.activeLayer()
    # Get geometryType(): 0 = points; 1 = lines; 2 = polygons
    if layer.geometryType() == 1:
        length = 0
        # Get total length
        for f in layer.selectedFeatures():
            length += f.geometry().length()
        print "Length: " + str(length) + " m"
    if layer.geometryType() == 2:
        area = 0
        # Get total area
        for f in layer.selectedFeatures():
            area += f.geometry().area()
        print "Area: " + str(area) + " m^2"
    else:
        pass

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    if layer.geometryType() == 1 or layer.geometryType() == 2:
        layer.selectionChanged.connect(calc_Geom)

Example (selected features highlighted yellow):

Result

1
  • @user35594 - Most welcome, glad it works =)
    – Joseph
    Commented Sep 19, 2016 at 14:06

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.