Source code: XYZ tile URLs for QGIS: 27 free basemaps, checked and ready to load
Runnable Python scripts, requirements and console output for the tutorial “XYZ tile URLs for QGIS: 27 free basemaps, checked and ready to load”.
Last updated
These are the exact scripts used to produce every figure and number in XYZ tile URLs for QGIS: 27 free basemaps, checked and ready to load. Download them, install the requirements into a fresh virtual environment and run them from this folder.
- capture_scene.py
- contact_sheet.py
- xyz_tile_catalogue.py
- requirements.txt
- console.txt: the console output recorded when we ran it
python -m venv .venv.venv\Scripts\activate # macOS/Linux: source .venv/bin/activatepip install -r requirements.txtpython capture_scene.pycapture_scene.py
"""QGIS screenshots for the XYZ tile URL list (run by tools/qgis-capture/scene_shot.ps1).
1. Writes the connections in technicalgis-xyz-connections.xml into the throwaway profile.2. Adds Esri World Imagery with the Esri road and label overlays (an open "hybrid") over Keswick.3. Grabs the main window with the Browser panel listing the loaded connections.4. Opens Data Source Manager > XYZ Tiles > New, fills in OpenTopoMap and grabs the dialogue."""from pathlib import Path
from qgis.core import ( QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsDataSourceUri, QgsProject, QgsRasterLayer, QgsRectangle, QgsSettings,)from qgis.gui import QgsBrowserTreeViewfrom qgis.PyQt.QtCore import QTimerfrom qgis.PyQt.QtWidgets import QAbstractButton, QApplication, QDockWidget, QLineEdit, QPushButton, QSpinBox, QWidget
HERE = Path(__file__).parentXML = HERE / "technicalgis-xyz-connections.xml"
def steps(iface, shot, log): st = {}
def setup(): log("setup") mw = iface.mainWindow() mw.showNormal() mw.resize(1500, 900) mw.move(40, 40) # The import itself was tested headless in xyz_tile_catalogue.py; here the same XML is written # straight into settings so no confirmation prompt can block the capture. import xml.etree.ElementTree as ET s = QgsSettings() s.remove("connections/xyz") for item in ET.parse(XML).getroot(): for key in ("url", "zmin", "zmax", "authcfg", "username", "password", "referer", "tilePixelRatio"): s.setValue(f"connections/xyz/items/{item.get('name')}/{key}", item.get(key, "")) iface.reloadConnections() s = QgsSettings() s.beginGroup("connections/xyz/items") log(f"connections: {len(s.childGroups())}") s.endGroup() for dock in mw.findChildren(QDockWidget): if dock.objectName() not in ("Browser", "Layers"): dock.hide() project = QgsProject.instance() project.setCrs(QgsCoordinateReferenceSystem("EPSG:3857")) for name in ("Esri World Imagery", "Esri Transportation (roads)", "Esri Boundaries and Places (labels)"): p = f"connections/xyz/items/{name}" uri = QgsDataSourceUri() uri.setParam("type", "xyz") uri.setParam("url", s.value(f"{p}/url")) uri.setParam("zmin", "0") uri.setParam("zmax", str(s.value(f"{p}/zmax"))) layer = QgsRasterLayer(bytes(uri.encodedUri()).decode(), name, "wms") log(f"{name}: valid={layer.isValid()}") project.addMapLayer(layer) tr = QgsCoordinateTransform(QgsCoordinateReferenceSystem("EPSG:4326"), project.crs(), project) iface.mapCanvas().setExtent(tr.transformBoundingBox(QgsRectangle(-3.20, 54.565, -3.10, 54.612))) iface.mapCanvas().refresh()
def zoom(): project = QgsProject.instance() canvas = iface.mapCanvas() canvas.setDestinationCrs(project.crs()) tr = QgsCoordinateTransform(QgsCoordinateReferenceSystem("EPSG:4326"), project.crs(), project) canvas.setExtent(tr.transformBoundingBox(QgsRectangle(-3.20, 54.565, -3.10, 54.612))) canvas.refresh() log(f"scale {canvas.scale():.0f}")
def expand_browser(): tree = iface.mainWindow().findChild(QDockWidget, "Browser").findChild(QgsBrowserTreeView) model = tree.model() for r in range(model.rowCount()): idx = model.index(r, 0) if model.data(idx) == "XYZ Tiles": tree.expand(idx) tree.scrollTo(idx, tree.PositionAtTop) st["tree"] = tree log("browser expanded")
def grab_main(): shot(iface.mainWindow(), "01-qgis-xyz-connections-hybrid.png")
def open_dsm(): iface.openDataSourceManagerPage("XYZ")
def click_new(): dsm = next(w for w in QApplication.topLevelWidgets() if w.metaObject().className() == "QgsDataSourceManagerDialog") dsm.show() dsm.raise_() QApplication.processEvents() st["dsm"] = dsm page = next((w for w in dsm.findChildren(QWidget) if w.metaObject().className() == "QgsXyzSourceSelect"), None) log(f"data source manager visible={dsm.isVisible()} xyz page={page is not None}") for b in (page or dsm).findChildren(QAbstractButton): if b.text().replace("&", "") == "New": QTimer.singleShot(0, b.click) log("clicked New") return def fill_dialog(): dlg = QApplication.activeModalWidget() log(f"modal={dlg.metaObject().className() if dlg else None}") st["dlg"] = dlg edits = {e.objectName(): e for e in dlg.findChildren(QLineEdit)} edits["mEditName"].setText("OpenTopoMap") edits["mEditUrl"].setText("https://a.tile.opentopomap.org/{z}/{x}/{y}.png") for cb in dlg.findChildren(QAbstractButton): if cb.objectName() == "mCheckBoxZMax": cb.setChecked(True) for sp in dlg.findChildren(QSpinBox): if sp.objectName() == "mSpinZMax": sp.setValue(17) dlg.resize(620, dlg.height()) log("dialog filled: " + ", ".join(sorted(edits)))
def grab_dialog(): shot(st["dlg"], "02-qgis-xyz-connection-dialog.png") st["dlg"].reject() st["dsm"].close()
return [ (500, setup), (2000, zoom), (1000, expand_browser), (15000, grab_main), (500, open_dsm), (2500, click_new), (2000, fill_dialog), (1000, grab_dialog), ]contact_sheet.py
"""Combine the QGIS renders from xyz_tile_catalogue.py into labelled contact sheets.
Run with any Python that has Pillow, after xyz_tile_catalogue.py: python contact_sheet.py"""import jsonfrom pathlib import Path
from PIL import Image, ImageDraw, ImageFont
OUT = Path(__file__).parent / "output"RENDERS = OUT / "renders"
def slug(name: str) -> str: s = "".join(c if c.isalnum() else "-" for c in name.lower()) while "--" in s: s = s.replace("--", "-") return s.strip("-")
def font(size): for f in ("segoeui.ttf", "arial.ttf", "DejaVuSans.ttf"): try: return ImageFont.truetype(f, size) except OSError: pass return ImageFont.load_default()
def sheet(items, cols, path, tile=(400, 250)): rows = (len(items) + cols - 1) // cols pad, label_h = 10, 30 w = cols * (tile[0] + pad) + pad h = rows * (tile[1] + label_h + pad) + pad img = Image.new("RGB", (w, h), "white") draw = ImageDraw.Draw(img) f = font(17) for i, (label, file) in enumerate(items): r, c = divmod(i, cols) x = pad + c * (tile[0] + pad) y = pad + r * (tile[1] + label_h + pad) im = Image.open(RENDERS / file).convert("RGB").resize(tile, Image.LANCZOS) img.paste(im, (x, y + label_h)) draw.rectangle([x, y + label_h, x + tile[0] - 1, y + label_h + tile[1] - 1], outline="#c8c8c8") draw.text((x, y + 4), label, fill="#1f2328", font=f) img.save(path, optimize=True) print(f"wrote {path.name}: {len(items)} panels, {w} x {h} px")
def main(): checks = json.loads((OUT / "tile_checks.json").read_text(encoding="utf-8")) keswick = [(r["name"], f"{slug(r['name'])}.png") for r in checks if r["view"] == "keswick" and r["group"] != "Esri overlays"] keswick.append(("Esri imagery + roads + labels (hybrid)", "esri-hybrid.png")) national = [(r["name"], f"{slug(r['name'])}.png") for r in checks if r["group"] == "National"] sheet(keswick, 4, OUT / "contact-sheet-keswick.png") sheet(national, 4, OUT / "contact-sheet-national.png")
if __name__ == "__main__": main()xyz_tile_catalogue.py
"""Check, render and export a catalogue of XYZ basemaps for QGIS.
For every basemap that needs no key, this script 1. requests one sample tile and records the HTTP status and size, 2. adds the URL to QGIS as an XYZ layer and renders the same view to PNG, 3. writes all connections to an XML file that QGIS can load with Browser > XYZ Tiles > Load Connections..., 4. loads that XML back into a clean QGIS profile to prove it imports.
Run it with QGIS's own Python, for example on Windows: "C:\\Program Files\\QGIS 3.40.12\\bin\\python-qgis-ltr.bat" xyz_tile_catalogue.pyTested with QGIS 3.40.12-Bratislava."""import jsonimport mathimport osimport sysimport tempfileimport timefrom pathlib import Pathfrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopenfrom xml.sax.saxutils import quoteattr
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from qgis.core import ( # noqa: E402 Qgis, QgsApplication, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsDataSourceUri, QgsMapRendererParallelJob, QgsMapSettings, QgsProject, QgsRasterLayer, QgsRectangle, QgsSettings,)from qgis.PyQt.QtCore import QSize # noqa: E402from qgis.PyQt.QtGui import QColor # noqa: E402
HERE = Path(__file__).parentOUT = HERE / "output"RENDERS = OUT / "renders"RENDERS.mkdir(parents=True, exist_ok=True)USER_AGENT = "TechnicalGIS-tutorial-check/1.0 (+https://www.technicalgis.com/)"
# Views in WGS84 (west, south, east, north). Global basemaps are all drawn# over Keswick and Derwentwater in the Lake District, so they can be compared.VIEWS = { "keswick": (-3.215, 54.555, -3.085, 54.620), "amsterdam": (4.860, 52.350, 4.940, 52.385), "paris": (2.300, 48.840, 2.380, 48.875), "vienna": (16.330, 48.190, 16.410, 48.225), "bern": (7.410, 46.935, 7.470, 46.960), "dresden": (13.700, 51.035, 13.780, 51.065), "grand-canyon": (-112.20, 36.03, -112.02, 36.13),}
# name, url, zmax, view, groupCATALOGUE = [ ("OpenStreetMap", "https://tile.openstreetmap.org/{z}/{x}/{y}.png", 19, "keswick", "OpenStreetMap styles"), ("OpenStreetMap France", "https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png", 20, "keswick", "OpenStreetMap styles"), ("Humanitarian OSM (HOT)", "https://a.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", 20, "keswick", "OpenStreetMap styles"), ("CyclOSM", "https://a.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png", 20, "keswick", "OpenStreetMap styles"), ("OpenTopoMap", "https://a.tile.opentopomap.org/{z}/{x}/{y}.png", 17, "keswick", "OpenStreetMap styles"), ("Esri World Imagery", "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", 19, "keswick", "Esri"), ("Esri World Street Map", "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", 19, "keswick", "Esri"), ("Esri World Topographic Map", "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", 19, "keswick", "Esri"), ("Esri World Hillshade", "https://server.arcgisonline.com/ArcGIS/rest/services/Elevation/World_Hillshade/MapServer/tile/{z}/{y}/{x}", 16, "keswick", "Esri"), ("Esri Light Gray Canvas", "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}", 16, "keswick", "Esri"), ("Esri Dark Gray Canvas", "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}", 16, "keswick", "Esri"), ("Esri Boundaries and Places (labels)", "https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}", 19, "keswick", "Esri overlays"), ("Esri Transportation (roads)", "https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer/tile/{z}/{y}/{x}", 19, "keswick", "Esri overlays"), ("Sentinel-2 cloudless 2016 (EOX)", "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless_3857/default/g/{z}/{y}/{x}.jpg", 14, "keswick", "EOX"), ("Sentinel-2 cloudless 2025 (EOX)", "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2025_3857/default/g/{z}/{y}/{x}.jpg", 14, "keswick", "EOX"), ("EOX Terrain Light", "https://tiles.maps.eox.at/wmts/1.0.0/terrain-light_3857/default/g/{z}/{y}/{x}.jpg", 16, "keswick", "EOX"), ("USGS Imagery Only", "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}", 16, "grand-canyon", "National"), ("USGS Topo", "https://basemap.nationalmap.gov/arcgis/rest/services/USGSTopo/MapServer/tile/{z}/{y}/{x}", 16, "grand-canyon", "National"), ("PDOK Luchtfoto (Netherlands)", "https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg", 19, "amsterdam", "National"), ("PDOK BRT Achtergrondkaart (Netherlands)", "https://service.pdok.nl/brt/achtergrondkaart/wmts/v2_0/standaard/EPSG:3857/{z}/{x}/{y}.png", 19, "amsterdam", "National"), ("IGN Orthophotos (France)", "https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpeg", 19, "paris", "National"), ("IGN Plan IGN v2 (France)", "https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/png", 19, "paris", "National"), ("basemap.at (Austria)", "https://mapsneu.wien.gv.at/basemap/geolandbasemap/normal/google3857/{z}/{y}/{x}.png", 19, "vienna", "National"), ("basemap.at Orthofoto (Austria)", "https://mapsneu.wien.gv.at/basemap/bmaporthofoto30cm/normal/google3857/{z}/{y}/{x}.jpeg", 19, "vienna", "National"), ("swisstopo SWISSIMAGE (Switzerland)", "https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg", 20, "bern", "National"), ("swisstopo national map (Switzerland)", "https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg", 18, "bern", "National"), ("BKG TopPlusOpen (Germany)", "https://sgx.geodatenzentrum.de/wmts_topplus_open/tile/1.0.0/web/default/WEBMERCATOR/{z}/{y}/{x}.png", 18, "dresden", "National"),]
# A "hybrid" built from open layers: imagery with Esri's road and label overlays on top.HYBRID = ["Esri World Imagery", "Esri Transportation (roads)", "Esri Boundaries and Places (labels)"]
def tile_for(view: str, z: int): """Column and row of the tile at the centre of a view.""" w, s, e, n = VIEWS[view] lon, lat = (w + e) / 2, (s + n) / 2 x = int((lon + 180) / 360 * 2**z) y = int((1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * 2**z) return x, y
def fill(url: str, z: int, x: int, y: int) -> str: return url.replace("{z}", str(z)).replace("{x}", str(x)).replace("{y}", str(y))
def check_tile(url: str, view: str) -> dict: z = 13 x, y = tile_for(view, z) req = Request(fill(url, z, x, y), headers={"User-Agent": USER_AGENT}) for attempt in (1, 2): t0 = time.time() try: with urlopen(req, timeout=30) as r: body = r.read() status, ctype = r.status, r.headers.get("Content-Type") break except HTTPError as err: body, status, ctype = b"", err.code, err.headers.get("Content-Type") break except OSError as err: # timeouts and dropped connections: try once more body, status, ctype = b"", f"error: {err}", None return {"status": status, "type": ctype, "bytes": len(body), "attempts": attempt, "ms": round((time.time() - t0) * 1000), "tile": f"{z}/{x}/{y}"}
def xyz_source(url: str, zmax: int) -> str: uri = QgsDataSourceUri() uri.setParam("type", "xyz") uri.setParam("url", url) uri.setParam("zmin", "0") uri.setParam("zmax", str(zmax)) return bytes(uri.encodedUri()).decode()
def render(layers, view: str, path: Path, size=(640, 400)) -> int: wgs84 = QgsCoordinateReferenceSystem("EPSG:4326") merc = QgsCoordinateReferenceSystem("EPSG:3857") extent = QgsCoordinateTransform(wgs84, merc, QgsProject.instance()).transformBoundingBox(QgsRectangle(*VIEWS[view])) settings = QgsMapSettings() settings.setLayers(layers) settings.setDestinationCrs(merc) settings.setExtent(extent) settings.setOutputSize(QSize(*size)) settings.setBackgroundColor(QColor("white")) job = QgsMapRendererParallelJob(settings) job.start() job.waitForFinished() job.renderedImage().save(str(path)) return len(job.errors())
def write_connections_xml(path: Path) -> None: lines = ["<!DOCTYPE connections>", '<qgsXYZTilesConnections version="1.0">'] for name, url, zmax, _view, _group in CATALOGUE: lines.append( f" <xyztiles name={quoteattr(name)} url={quoteattr(url)} zmin=\"0\" zmax=\"{zmax}\" " 'authcfg="" username="" password="" referer="" tilePixelRatio="0"/>' ) lines.append("</qgsXYZTilesConnections>") path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def slug(name: str) -> str: s = "".join(c if c.isalnum() else "-" for c in name.lower()) while "--" in s: s = s.replace("--", "-") return s.strip("-")
def main() -> None: profile = tempfile.mkdtemp(prefix="qgis-xyz-") qgs = QgsApplication([], True, profile) qgs.initQgis() print("QGIS", Qgis.version())
results = [] layers = {} for name, url, zmax, view, group in CATALOGUE: http = check_tile(url, view) layer = QgsRasterLayer(xyz_source(url, zmax), name, "wms") QgsProject.instance().addMapLayer(layer, False) layers[name] = layer errors = render([layer], view, RENDERS / f"{slug(name)}.png") results.append({"name": name, "group": group, "view": view, "valid": layer.isValid(), "render_errors": errors, **http}) print(f"{name:40s} HTTP {http['status']} {http['bytes']:>7} B {http['ms']:>5} ms (try {http['attempts']}) " f"valid={layer.isValid()} render_errors={errors}")
errors = render([layers[n] for n in reversed(HYBRID)], "keswick", RENDERS / "esri-hybrid.png") print(f"{'Esri hybrid (imagery + roads + labels)':40s} render_errors={errors}")
xml_path = HERE / "technicalgis-xyz-connections.xml" # published at /code/xyz-tile-urls-qgis/ write_connections_xml(xml_path) print(f"wrote {xml_path.name} with {len(CATALOGUE)} connections")
# Load the XML into this clean profile with QGIS's own Load Connections dialogue. from qgis.gui import QgsManageConnectionsDialog
# Start from no XYZ connections, so QGIS never stops to ask about overwriting one. QgsSettings().remove("connections/xyz") dlg = QgsManageConnectionsDialog(None, QgsManageConnectionsDialog.Import, QgsManageConnectionsDialog.XyzTiles, str(xml_path)) dlg.selectAll() dlg.doExportImport() s = QgsSettings() s.beginGroup("connections/xyz/items") imported = s.childGroups() s.endGroup() ok = all(name in imported for name, *_ in CATALOGUE) print(f"loaded into a clean profile: {len(imported)} XYZ connections, all {len(CATALOGUE)} present={ok}") sample = "Esri World Imagery" print(f" {sample}: url={QgsSettings().value(f'connections/xyz/items/{sample}/url')}")
(OUT / "tile_checks.json").write_text(json.dumps(results, indent=2), encoding="utf-8") qgs.exitQgis() sys.exit(0 if ok and all(r["status"] == 200 for r in results) else 1)
if __name__ == "__main__": main()