I have a vector layer with Multilinestrings and used the field calculator to add a field ("length") with the calculated $length of each feature. I know the field values are correct. Now, if I calculate the length of the features with PyQGIS, I get different, wrong results. Does anybody know, what could be the reason? I don't know where to start looking for the error.

Code example:

layer = iface.activeLayer()
feature = next(layer.getFeatures())
print(feature.geometry().length() / feature['length'])

Result: 1.67


The $length expression function states that

The length calculated by this function respects both the current project's ellipsoid setting and distance unit settings. For example, if an ellipsoid has been set for the project then the calculated length will be ellipsoidal, and if no ellipsoid is set then the calculated length will be planimetric.

QgsGeometry.length on the other hand says

Returns the length of geometry using GEOS

Sadly this is not very helpful if you don't know what GEOS means. GEOS is the underlying geometry engine and it has no idea about coordinate systems, ellipsoids and all that spatial stuff. It is purely about geometry. This means QgsGeometry.length will consider all coordinate values of the geometry as flat cartesian coordinates. You might know they are geographic/ellipsoidal, GEOS does not.

If you are in a length-preserving projection with meaningful units (meters), the result will (almost) be the measurement as if done in the real world. But in all other cases, the results from this function are rather useless.


Your layer's coordinate system is probably a Geographic one (meaning Ellipsoidal here), therefore the distance calculated in degree dimension. To solve this issue, first you have to a pick a proper Projected coordinate system, and save the layer in that coordinate system (Save as, change CRS).

You can find a proper Projected coordinate system at https://epsg.io, e.g. search for your country.

After the projection, the lenght() method's result will be fine.

  • I sure hope that QGIS provides functions for calculating "true" lengths without having to reproject manually. – bugmenot123 Aug 16 '19 at 13:19
  • Maybe try it... – pnz Aug 18 '19 at 19:45
  • Yes, see QgsDistanceArea class – ndawson Aug 20 '19 at 18:46

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.