Adding basemaps to PyQGIS maps in Jupyter notebooks

By neub9
2 Min Read

In the previous post, we explored how to integrate QGIS maps into Jupyter notebooks.

Today, we’ll take the next step and add basemaps to our maps. This turned out to be more challenging than expected. I initially struggled with “invalid” OSM tile layers until I discovered that my QGIS application instance was missing the “WMS” provider.

Additionally, getting basemaps to work also requires us to handle layer and project CRSes and on-the-fly reprojections. So let’s get started:

      from IPython.display import Image
      from PyQt5.QtGui import QColor
      from PyQt5.QtWidgets import QApplication
      from qgis.gui import QgsMapCanvas
      # ... (additional code)

To add an OSM basemap, we use the xyz tiles option of the WMS provider:

      # ... (existing code)

If there are issues with the WMS provider, rlayer.error().summary() will point them out.

With both the vector layer and the basemap ready, we can finally plot the map:

      # ... (existing code)

Of course, we can get more creative and style our vector layers:

      # ... (existing code)

And to switch to other basemaps, we just need to update the URL accordingly, for example, to load Carto tiles instead:

      # ... (existing code for Carto tiles)

You can find the whole notebook at:

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *