Wednesday 14 August 2019

pyqgis - How to access CRS of shapefile in standalone script?


I'm trying to access the CRS of a layer and use this to create a grid. I followed the answer in this post which works great in QGIS but I would like it to work in a standalone script. Here is a snippet:


for fname in glob.glob("C:\Users\moi\Desktop\Test\Grid\\" + "*.shp"):

extent = QgsVectorLayer( fname, '', 'ogr' ).extent()
centerx = (extent.xMinimum() + extent.xMaximum()) / 2
centery = (extent.yMinimum() + extent.yMaximum()) / 2
width = extent.xMaximum() - extent.xMinimum()

height = extent.yMaximum() - extent.yMinimum()
CRS = QgsMapLayer.crs(fname).authid()

general.runalg("qgis:creategrid", 1000, 1000, width, height, centerx, centery, 1, CRS, None)

Running the above gives me the following error message:



TypeError: QgsMapLayer.crs(): first argument of unbound method must have type 'QgsMapLayer'




Answer




Bleh, answer was simple.


Just had to replace what I originally wrote:


CRS = QgsMapLayer.crs(fname).authid()

With this:


CRS = QgsVectorLayer( fname, '', 'ogr' ).crs().authid()

Works a treat, hope this helps someone!


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...