I'm currently developing a small plugin for QGIS where the objective is to show various locations on a map. For the users convenience I want to load OSM after I have loaded all the locations into QGIS.
So far this is what i got.
def load_osm(self):
url_params = 'type=xyz&url=https://tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG4326'
osm_layer = QgsRasterLayer(url_params, 'OpenStreetMap', 'wms')
if osm_layer.isValid():
QgsProject.instance().addMapLayer(osm_layer)
else:
QgsMessageLog.logMessage('The layer is not valid')
From the code above this is the result.
As you can see loading the OSM like I'm currently doing in the code, is messing up the zone and is not zooming. In the 2nd picture I imported the locations first and then dragged and dropped the OSM layer from the Explorer in QGIS.
Best Answer
Thanks for all the help, managed to get it to work by defining the CRS of the map layer before adding the map layer like this.
For the zoom to work properly i defined the correct layer as the active layer and used the QTimer class to delay the zoom until the layers actually was loaded and shown on the canvas like this.