11

I am trying to set the projection on a raster to match that of a vector point layer. Thus I need to find out what is the projection of a given layer, to use it in the GDAL.Dataset.SetProjection() so that I can create the GeoTIFF with the appropriate projection.

How do I do that in QGIS using Python?

3
  • Another way to put it is: How to get the EPSG for the Layer?
    – fccoelho
    Commented Sep 25, 2012 at 11:55
  • Do you want to reproject the raster to the vector's CRS using Python? Please try to clarify.
    – underdark
    Commented Sep 25, 2012 at 12:01
  • @fccoelho In the python console: iface.activeLayer().crs().postgisSrid() returns only the EPSG code as an integer.
    – Stefan
    Commented Jun 20, 2018 at 14:36

2 Answers 2

22

Short answer

qgis.utils.iface.activeLayer().crs().authid()
# returns: 'EPSG:26913'

Explanation

qgis.utils.iface.activeLayer() returns a reference to the active QgsMapLayer.

QgsMapLayer.crs() returns the crs or QgsCoordinateReferenceSystem for the layer.

QgsCoordinateReferenceSystem.authid() returns the Authority identifier for the crs as a String.

However, this is assuming there is an active layer, it is of a vector type, and it has a valid crs. You will want to test for validity of those items before committing to reprojecting a raster.

If you are reprojecting, using GDAL.Dataset.SetProjection() will not suffice, since it will only assign a projection and not reproject (warp) the raster to the same as your vector layer.

1
2

You can get the active layer's CRS with:

layer = iface.activeLayer()
lyrCRS = layer.crs().authid() # returns a reference to the active QgsMapLayer

print(lyrCRS)

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.