TransWikia.com

Error when zooming to layer in PyQGIS application. On-the-fly transformation the issue?

Geographic Information Systems Asked by Alex92 on February 28, 2021

I am trying to set the extent of my window to a layer on my canvas. This has worked smoothly until I started using Web Mercator maps instead of WGS84 maps. My features are getting their geolocation from an external source which feeds in decimal degrees, so I am using on-the-fly transformation to get it projected properly on Web Mercator. The problem is that in my code, when I set the extent to my layer, it appears to try to do it in decimal degrees, putting my window in the middle of the Atlantic Ocean.

My extent code is very simple:

self.mapCanvas.setExtent(self.myLayer.extent())

My canvas CRS code is straightforward as well:

self.mapCanvas = QgsMapCanvas()
self.mapCanvas.useImageToRender(False)
self.mapCanvas.setCanvasColor(Qt.white)
self.mapCanvas.setCrsTransformEnabled(True)
self.mapCanvas.setDestinationCrs(QgsCoordinateReferenceSystem(3857, QgsCoordinateReferenceSystem.EpsgCrsId))
self.mapCanvas.show()

Is anything not right?

One Answer

If the CRS of the canvas and the layer are different, you must reproject the layer extent to the canvas CRS before zooming. Try this:

mapCanvas = iface.mapCanvas()
xform = QgsCoordinateTransform(myLayer.crs(), mapCanvas.mapRenderer().destinationCrs())
mapCanvas.setExtent(xform.transform(myLayer.extent()))
mapCanvas.refresh()

Answered by JTh on February 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP