[GIS] Get list of CRS in QGIS by python

coordinate systemepsgqgisqgis-plugins

It is possible to get list/dictionary of "Recently used coordinate reference system" from QGIS by python?

Or get list of all "Coordinate reference systems of the world" also from QGIS by python.

Best Answer

The recently used projections are stored in your user settings. Here is an example of the keys and some sample values:

  • UI/recentProjections=932, 3452
  • UI/recentProjectionsProj4="+proj=aea +lat_1=55 +lat_2=65 +lat_0=50 +lon_0=-154 +x_0=0 +y_0=0 +datum=NAD27 +units=us-ft +no_defs", "+proj=longlat +datum=WGS84 +no_defs"
  • UI/recentProjectionsAuthId=EPSG:2964, EPSG:4326

For example, you could get the AuthIds like so:

>>> QSettings().value('UI/recentProjectionsAuthId')
[u'EPSG:4326', u'EPSG:3338', u'EPSG:2964', u'EPSG:900913', u'EPSG:3035', u'EPSG:32733', u'EPSG:4267']

All of the coordinate systems are stored in the srs.db file found in the resources directory of your QGIS install. You can use the Python sqlite3 module to query this database and get a list of all the coordinate systems:

import sqlite3
con = sqlite3.connect(QgsApplication.srsDbFilePath())
cur = con.cursor()
cur.execute('select * from vw_srs')
rows = cur.fetchall()
for crs in rows:
  # do something...
  print crs
cur.close()
con.close()