PyQGIS – Transforming Single QgsGeometry Object from One CRS to Another

coordinate systemgeometrylinepyqgis

I have a polyline layer with roads in WGS84 that covers several UTM zones. For every road I need to place a set of points at different distances (in metres). To do so I want to reproject each road to respective UTM zone, create points in this UTM zone, reproject points to WGS84 and add them to respectful layer. There is aQgsCoordinateTransform() class that allows to perform transformation for individual points, but it doesn't accept polylines. I guess I could manually disassemble polylines into the set of points, transform each of them and recreate a polyline, but I hope that there is a build-in method or class that I overlooked, that allows to transform individual polylines.

Best Answer

use QgsGeometry.transform( QgsCoordinateTransform tr ). for example after created your instance of QgsCoordinateTransform with source and dest crs, for each geometry instance do:

sourceCrs = QgsCoordinateReferenceSystem(4326)
destCrs = QgsCoordinateReferenceSystem(2154)
tr = QgsCoordinateTransform(sourceCrs, destCrs, QgsProject.instance())
myGeometryInstance.transform(tr)

https://qgis.org/api/classQgsCoordinateTransform.html#aa5ad428819ac020f8f5716e835ab754f

beware that the transformation (applying QgsCoordinateTransform) will change the QgsGeometry instance.