4

I am writing a plugin to import some files into qgis. The files initially have coordinates in lat lon, but I want to reproject them to a local projection during the import.

So, I can set the CRS on the layer I am importing in and and I know that my imported points are in WGS 84, so what I want to do is similiar to what I would have done in postgis with

ST_Tranform(ST_SetSRID(ST_MakePoint(15, 60),4326),32633);

to import the point into a layer WGS84 UTM zone33N

But in qgis, how can I make a PointXY() with a CRS and then reproject it to another CRS?

(I know I can read everything into a layer with CRS 4326 and then reproject the entire layer into a new layer, but I would prefer to do it without having to make an extra layer)

2 Answers 2

7

You can use the following recipe

# Create QgsGeometry from QgsPointXY
geom = QgsGeometry.fromPointXY (QgsPointXY(5,20))
# Prepare crs source and destination and instanciate a transform function
sourceCrs = QgsCoordinateReferenceSystem(4326)
destCrs = QgsCoordinateReferenceSystem(2154)
tr = QgsCoordinateTransform(sourceCrs, destCrs, QgsProject.instance())

# Option 1
# Clone (to not transform in place the geometry)
geom2 = QgsGeometry(geom)
geom2.transform(tr)
geom2.asPoint() # QgsPointXY

# Option 2, transform in place and avoid a copy. Better for your scenario
geom.transform(tr)
geom.asPoint() # QgsPointXY

# Option 3, Use the transform function to directly reproject QgsPointXY
# without intermediate QgsGeometry. Added due to your answer to compile solutions
tr.transform(QgsPointXY(5,20))

Sample adapted from Transforming single QgsGeometry object from one CRS to another using PyQGIS? to fit your request

1
  • Great! The problem was to find the right level to do the tranformation on (i.e. the QgsGeometry object...) Commented Feb 4, 2020 at 20:15
5

That is, for some reason, I ended up having to do

 point = QgsPointXY(float(lon), float(lat)) 
 point = tr.transform(point)
 geom = QgsGeometry.fromPointXY(point)

Trying to do geom.transform(tr) did for some reason not work for me

3
  • Nice. Did not see that transform instance can be applied directly to a QgsPointXY
    – ThomasG77
    Commented Feb 5, 2020 at 8:10
  • What is prpoint? Commented Jan 2, 2022 at 18:14
  • Typo, strange nobody has noticed earlier... Commented Jan 3, 2022 at 7:54

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.