Within a plugin I am developing I select features and for each line feature selected I get the feature distance using:


I also get the total length at the end using:

totallength = totallength + distance.measureLength(feature.geometry())

I display the total length in a message box but I don't know how to get the correct units of measure using pyqgis. How do I know if I should use feet or meters?

I tried using:


but that returns a value of 6. Why?


The distance object you have is a QgsDistanceArea.

If you have a look at the docs, the distance.lengthUnits() method returns a QgsUnitTypes.DistanceUnit code. QgsUnitTypes.DistanceUnit is an enum, that is, it has codes for each of its values.

You can get the value corresponding to certain code, i.e., the display string for the units in this way:

QgsUnitTypes.toString(6)  # degrees

You'll get the same using this recommended way:

QgsUnitTypes.toString(distance.lengthUnits())  # degrees

Of course, you can also find the method toString() in the docs.

NOTE: You can tell the QgsDistanceArea object the CRS you want to use.

If you have the EPSG code, do something like this:

crs = QgsCoordinateReferenceSystem(2272, QgsCoordinateReferenceSystem.EpsgCrsId)
d.setSourceCrs(crs, QgsProject.instance().transformContext())

If you have a layer object with a CRS set, do something like this:

d.setSourceCrs(layer.sourceCrs(), QgsProject.instance().transformContext())

Next time you ask for length units, you'll get those defined in the CRS you passed to the QgsDistanceArea.

  • Why would it return 6 (degrees) as the units? My the project and shapefile are using EPSG:2272. – GreyHippo Nov 11 '19 at 16:35
  • That's another question. I updated the answer with some notes regarding units of a layer. – Germán Carrillo Nov 11 '19 at 17:23

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.