Saturday, 25 August 2018

python - how to get the projection from a vectorlayer in qgis?


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 Python)



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...