PyQGIS Projection Issue – Resolving OpenStreetMap Loading Problems

openstreetmappyqgisqgis-plugins

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.

enter image description here

What I want to achieve.
enter image description here

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.

file_to_qgis = "file:///{}{}{}?delimiter={}&xField={}&yField={}".\
            format(os.getcwd(), "/", file, ",", "stop_lon", "stop_lat")
        layer_stoppesteder = QgsVectorLayer(file_to_qgis, "vtfk-stoppesteder", "delimitedtext")
        crs = layer_stoppesteder.crs()
        crs.createFromId(4326)
        layer_stoppesteder.setCrs(crs)

""" 
Code to add the layer goes here. 
"""

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.

    def active_layer_changed(self):
        active_layer = QgsProject.instance().mapLayersByName('vtfk-stoppesteder')[0]
        iface.setActiveLayer(active_layer)

        timer = QTimer()
        timer.singleShot(2000, self.zoom_to_active_layer)

    def zoom_to_active_layer(self):
        iface.zoomToActiveLayer()
Related Question