"""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.py Tested with QGIS 3.40.12-Bratislava. """ import json import math import os import sys import tempfile import time from pathlib import Path from urllib.error import HTTPError from urllib.request import Request, urlopen from 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: E402 from qgis.PyQt.QtGui import QColor # noqa: E402 HERE = Path(__file__).parent OUT = 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, group CATALOGUE = [ ("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 = ["", ''] for name, url, zmax, _view, _group in CATALOGUE: lines.append( f" ' ) lines.append("") 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()