10

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?

Taras
  • 32,823
  • 4
  • 66
  • 137
fccoelho
  • 1,237
  • 5
  • 13
  • 22

2 Answers2

21

Short answer

qgis.utils.iface.activeLayer().crs().authid()
# returns: PyQt4.QtCore.QString(u'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 QString.

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.

dakcarto
  • 7,754
  • 26
  • 34
  • I ended up using: layer.srs() to get the layer and then srs.epsg to get the EPSG code for the layer. Then, to generate the geotiff: see here: https://github.com/fccoelho/spatialKDE/blob/master/kernel.py in the to_geotiff method. – fccoelho Sep 29 '12 at 16:23
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)

Taras
  • 32,823
  • 4
  • 66
  • 137
user107473
  • 21
  • 1