I suspect that the problem is a mis-match between your project CRS and your raster CRS. Bear in mind that the extent()
method of QgsMapLayer
returns a QgsRectangle
in the layer CRS. When you pass a QgsRectangle
object to QgsMapCanvas.setExtent()
, it must be in the same CRS as the canvas.
To work around this in a simple way, I would recommend using iface.zoomToActiveLayer()
instead.
The following script should work as expected:
from pathlib import Path
import requests
service_url = "mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}"
service_uri = "type=xyz&zmin=0&zmax=21&url=https://"+requests.utils.quote(service_url)
tms_layer = iface.addRasterLayer(service_uri, "Google Sat", "wms")
image="/media/patrice/DataDrive/GORiM/ManualFineTuning/GEE/S2_S025_Z12R.tif"
Cname = Path(image).stem
Zone = Cname.split('_')[-1]
rlayer = iface.addRasterLayer(image, Cname, "gdal")
rlayer.loadNamedStyle("/media/patrice/DataDrive/GORiM/ManualFineTuning/ImageNIRStyle.qml")
rlayer.triggerRepaint()
iface.setActiveLayer(rlayer)
iface.zoomToActiveLayer()
Otherwise, if you want to use iface.mapCanvas().setExtent()
you will need to transform the extent from the layer CRS to the project CRS. To do that you can use the QgsCoordinateTransform class.
E.g.
from pathlib import Path
import requests
service_url = "mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}"
service_uri = "type=xyz&zmin=0&zmax=21&url=https://"+requests.utils.quote(service_url)
tms_layer = iface.addRasterLayer(service_uri, "Google Sat", "wms")
image="/media/patrice/DataDrive/GORiM/ManualFineTuning/GEE/S2_S025_Z12R.tif"
Cname = Path(image).stem
Zone = Cname.split('_')[-1]
rlayer = iface.addRasterLayer(image, Cname, "gdal")
rlayer.loadNamedStyle("/media/patrice/DataDrive/GORiM/ManualFineTuning/ImageNIRStyle.qml")
rlayer.triggerRepaint()
def transform(rect):
rlayer_crs = rlayer.crs()
canvas_crs = QgsProject.instance().crs()
if rlayer_crs != canvas_crs:
xform = QgsCoordinateTransform(rlayer_crs, canvas_crs, QgsProject.instance())
rect = xform.transform(rect)
return rect
iface.mapCanvas().setExtent(transform(rlayer.extent()))