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:
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?
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()