"""QGIS essentials, part 1: turn a CSV of latitude and longitude into points. Runs in QGIS's own Python (no QGIS window needed): "C:\\Program Files\\QGIS 3.40.12\\bin\\python-qgis-ltr.bat" -u csv_to_points.py 1. Downloads the Environment Agency's list of rainfall gauges as CSV (Open Government Licence). 2. Loads it as a point layer exactly as Layer > Add Layer > Add Delimited Text Layer does: X field = long, Y field = lat, CRS = EPSG:4326. 3. Checks the result: rows skipped for missing coordinates, the extent, and how far each point lands from the Environment Agency's own British National Grid easting and northing. 4. Shows what happens if X and Y are swapped. 5. Saves the points to a GeoPackage, and runs the Processing tool Create points layer from table to show it gives the same layer. 6. Writes rainfall-gauges.qgz (OpenStreetMap basemap and the styled points) for the screenshots. """ import csv import math import sys import urllib.request from pathlib import Path from qgis.core import (QgsApplication, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsMarkerSymbol, QgsProject, QgsRasterLayer, QgsVectorFileWriter, QgsVectorLayer) HERE = Path(__file__).resolve().parent DATA = HERE / "data" OUT = HERE / "output" CSV_URL = "https://environment.data.gov.uk/flood-monitoring/id/stations.csv?parameter=rainfall&_limit=5000" CSV_PATH = DATA / "rainfall-stations.csv" DATA.mkdir(exist_ok=True) OUT.mkdir(exist_ok=True) qgs = QgsApplication([], False) qgs.initQgis() sys.path.append(str(Path(QgsApplication.prefixPath()) / "python" / "plugins")) import processing # noqa: E402 from processing.core.Processing import Processing # noqa: E402 Processing.initialize() if not CSV_PATH.exists(): urllib.request.urlretrieve(CSV_URL, CSV_PATH) with open(CSV_PATH, newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f)) blank = [r for r in rows if not r["lat"] or not r["long"]] print("=== The CSV ===") print(f"{CSV_PATH.name}: {len(rows)} rows, {len(rows[0])} columns") print(f"rows with no latitude or longitude: {len(blank)} ({', '.join(r['notation'] for r in blank)})") print(f"first row: {rows[0]['notation']} lat {rows[0]['lat']} long {rows[0]['long']}") def delimited(x, y): uri = (f"{CSV_PATH.as_uri()}?type=csv&delimiter=,&detectTypes=yes&xField={x}&yField={y}" "&crs=EPSG:4326&spatialIndex=yes&subsetIndex=no&watchFile=no") return QgsVectorLayer(uri, "Rainfall gauges", "delimitedtext") print("\n=== Add Delimited Text Layer (X = long, Y = lat) ===") layer = delimited("long", "lat") assert layer.isValid(), "layer failed to load" ext = layer.extent() nogeo = sum(1 for f in layer.getFeatures() if f.geometry().isNull()) print(f"valid: {layer.isValid()}, CRS {layer.crs().authid()}, {layer.featureCount()} features, {nogeo} with no geometry") print(f"extent: longitude {ext.xMinimum():.4f} to {ext.xMaximum():.4f}, latitude {ext.yMinimum():.4f} to {ext.yMaximum():.4f}") types = {f.name(): f.typeName() for f in layer.fields()} print(f"field types detected: lat {types['lat']}, long {types['long']}, easting {types['easting']}, " f"dateOpened {types['dateOpened']}, period {types['period']}") # Check every point against the Environment Agency's own grid reference. to_bng = QgsCoordinateTransform(layer.crs(), QgsCoordinateReferenceSystem("EPSG:27700"), QgsProject.instance()) diffs = [] for feat in layer.getFeatures(): if feat.geometry().isNull() or feat["easting"] in (None, "") or feat["northing"] in (None, ""): continue p = to_bng.transform(feat.geometry().asPoint()) diffs.append((math.hypot(p.x() - float(feat["easting"]), p.y() - float(feat["northing"])), feat["notation"])) diffs.sort() med = diffs[len(diffs) // 2][0] within = sum(d <= 100 for d, _ in diffs) print(f"checked against the EA easting/northing: {len(diffs)} points, median difference {med:.1f} m, " f"{within} ({100 * within / len(diffs):.1f}%) within 100 m, largest {diffs[-1][0]:.0f} m ({diffs[-1][1]})") print("\n=== The classic mistake: X = lat, Y = long ===") swapped = delimited("lat", "long") se = swapped.extent() print(f"{swapped.featureCount()} points, extent x {se.xMinimum():.2f} to {se.xMaximum():.2f}, y {se.yMinimum():.2f} to {se.yMaximum():.2f}") print("\n=== Save as GeoPackage ===") gpkg = OUT / "rainfall-gauges.gpkg" if gpkg.exists(): gpkg.unlink() opts = QgsVectorFileWriter.SaveVectorOptions() opts.driverName = "GPKG" opts.layerName = "rainfall_gauges" err = QgsVectorFileWriter.writeAsVectorFormatV3(layer, str(gpkg), QgsProject.instance().transformContext(), opts) assert err[0] == QgsVectorFileWriter.NoError, err saved = QgsVectorLayer(f"{gpkg}|layername=rainfall_gauges", "Rainfall gauges", "ogr") empty = sum(1 for f in saved.getFeatures() if f.geometry().isNull() or f.geometry().isEmpty()) print(f"{gpkg.name}: {saved.featureCount()} features, {empty} without a location, CRS {saved.crs().authid()}, " f"{gpkg.stat().st_size / 1024:.0f} KB") print("\n=== Processing: Create points layer from table ===") res = processing.run("native:createpointslayerfromtable", { "INPUT": str(CSV_PATH), "XFIELD": "long", "YFIELD": "lat", "ZFIELD": "", "MFIELD": "", "TARGET_CRS": "EPSG:4326", "OUTPUT": "TEMPORARY_OUTPUT"}) tool = res["OUTPUT"] nogeom = sum(1 for f in tool.getFeatures() if f.geometry().isNull()) print(f"{tool.featureCount()} features, of which {nogeom} have no geometry") # Project for the screenshots: OpenStreetMap under the gauges. proj = QgsProject.instance() proj.clear() proj.setCrs(QgsCoordinateReferenceSystem("EPSG:3857")) osm = QgsRasterLayer("type=xyz&url=https://tile.openstreetmap.org/{z}/{x}/{y}.png&zmax=19&zmin=0", "OpenStreetMap", "wms") gauges = QgsVectorLayer(f"{gpkg}|layername=rainfall_gauges", "Rainfall gauges", "ogr") gauges.renderer().setSymbol(QgsMarkerSymbol.createSimple( {"name": "circle", "color": "31,120,180", "outline_color": "255,255,255", "outline_width": "0.3", "size": "2.2"})) proj.addMapLayer(osm) proj.addMapLayer(gauges) proj.write(str(OUT / "rainfall-gauges.qgz")) print(f"\nproject saved: output\\rainfall-gauges.qgz") qgs.exitQgis()