I'm trying to open a raster image of 15x15Km with a google basemap with PyQGIS. When the code finishes, I want the map canvas to zoom into the raster image. It almost works and I can add rasters and even vectors, but if I add a basemap, it's like the basemap overides the zoom level. so this simple code:
#basemap
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
image=”/media/patrice/DataDrive/GORiM/ManualFineTuning/GEE/S2_S025_Z12R.tif”
Cname=os.path.basename(image)[:-4]
Zone=os.path.basename(image)[-8:-4]
Sample=os.path.basename(image)[3:7]
Cname=os.path.basename(image)[:-4]
rlayer = iface.addRasterLayer(image,Cname,"gdal")
vLayer = iface.activeLayer()
extent = vLayer.extent()
iface.mapCanvas().setExtent(extent)
iface.mapCanvas().refresh()
Loads the layer and the basemap but the display has the whole world, in the correct projection, but fully zoomed out.
I also tried to get the active layer by name:
Cname=os.path.basename(image)[:-4]
rlayer = iface.addRasterLayer(image,Cname,"gdal")
layer = QgsProject.instance().mapLayersByName(Cname)[0]
layer.loadNamedStyle('/media/patrice/DataDrive/GORiM/ManualFineTuning/ImageNIRStyle.qml')
layer.triggerRepaint()
layer = QgsProject.instance().mapLayersByName(Cname)[0]
extent = layer.extent()
iface.mapCanvas().setExtent(extent)
iface.mapCanvas().refresh()
With the same result and no error messages. I think the problem is in setting the active layer, but I have tried printing layer names and they match.
UPDATE
No luck with the answer below. Both snipets of code gave the same result. I also investigated the idea that it was a conflict between layer CRS and project crs by adding:
Cname = Path(image).stem
Zone = Cname.split('_')[-1]
crs=str(GetCRS(Zone[-1], Zone[-3:-1]))
QGIScrs=QgsCoordinateReferenceSystem(crs)
QgsProject.instance().setCrs(QGIScrs)
where GetCRS gets the EPSG code from the zone number. The zones seem correct and the project crs matches the layer crs. Also, the google basemap is centered on the correct spot and clearly not in 3857 or in 4326. So is this an actual bug?
Raster File Raster file sample below. It's a 3 band Sentinel 2 file generated by Google Earth Engine. If this matters, I'm using Ubuntu 20.04 and 3.22.
https://drive.google.com/file/d/1wakV7g_eYNjq0NFv27zAq_FUVvq7heZe/view?usp=sharing
rlayer
? If I understand you correctly, that is what you want. :D