9

Is it possible to set the project CRS of an project in QGIS via a Python command?

In my case the user should open QGIS, start my written plugin and this plugin will load spatial data which has the epsg code 31467 (Gauss Krueger Zone 3). Unfortunately QGIS default CRS is WGS84 an so I get into trouble with the units and the scale.

My first approach was to use this code:

    my_crs = core.QgsCoordinateReferenceSystem(31467, core.QgsCoordinateReferenceSystem.EpsgCrsId)
    self.iface.mapCanvas().mapRenderer().setDestinationCrs(my_crs)

This changes (after the data is already visualized) the CRS to Gauss Krueger Zone 3. At least the espg code in the lower right corner has changed. The units are still in degrees and the scale is totally wrong. 1:5000 in Gauss Krüger is 1:528822376 in WGS 84 (in my case in QGIS). After setting the project CRS manually in the properties the project crs is really GK3 and the scale and the units are right.

So my question is, can I set the project CRS in another way than I have done it? I want to avoid the manual way.


I solved the problem by adding the following code:

qgis.utils.iface.mapCanvas().setMapUnits(0)
qgis.utils.iface.mapCanvas().refresh()

This sets the units to meter and the scale is updated automatically. The 0 stands for meters, 1 is for foot, 2 is for degree and 3 for unknown.

7

Yes, its possible. The Openlayers plugin by Sourcepole automatically sets CRS to EPSG:3857.

Have a look at openlayers_layers.py and openlayers_plugin.py.

7

A little late to answer, but in case someone drops to that page from google, without having the plugin installed, http://www.purplelinux.co.nz provides good information on that.

The example found on purplelinux (which is working fine) suggest the following:

if iface.mapCanvas().mapRenderer().hasCrsTransformEnabled():
    my_crs = core.QgsCoordinateReferenceSystem(4326,core.QgsCoordinateReferenceSystem.EpsgCrsId)
    iface.mapCanvas().mapRenderer().setDestinationCrs(my_crs)


And you could even create a CRS by calling:

QgsCoordinateReferenceSystem("PROPERTY:ID")

which would be:

QgsCoordinateReferenceSystem("EPSG:31467")

which IMHO makes the code much more readable.

  • 1
    Note the code is for QGIS 2.X and you should see other answers listed here for QGIS3 code – Mr Purple Mar 7 at 5:03
3

Use this:

QgsProject.instance().setCrs(my_crs)
  • 1
    Works with QGIS3, when my_crs=QgsCoordinateReferenceSystem(4326) :) – axel_ande Sep 1 '18 at 4:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.