2

According to Calculating Polygon Main Angle using QGIS, it is possible to find the main_angle of a polygon by using a field expression like:

main_angle($geometry)

Can this function be called using PyQGIS but not as an expression but from the Python console or script as a way to get the main orientation angle of a polygon?

2 Answers 2

4

See: PyQGIS 101: Using expressions to compute new field values

layer = iface.activeLayer()
    
expression1 = QgsExpression('main_angle($geometry)')
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
angles = []
for f in layer.getFeatures():
    context.setFeature(f)
    mainangle = expression1.evaluate(context)
    angles.append(mainangle)

print(angles[:5])
#[159.525122844183, 48.41639305999172, 0.7305299973963884, 105.59960002436623, 157.79005356043308]
0
3

Another method in addition to @BERA:

layer = iface.activeLayer()
feats = layer.getFeatures()
for f in feats:
    geom = QgsGeometry(f.geometry())
    output_geometry, area, angle, width, height = geom.orientedMinimumBoundingBox()
    print(angle)

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.