Source code: QGIS: turn a CSV of latitude and longitude into points
Runnable Python scripts, requirements and console output for the tutorial “QGIS: turn a CSV of latitude and longitude into points”.
Last updated
These are the exact scripts used to produce every figure and number in QGIS: turn a CSV of latitude and longitude into points. Download them, install the requirements into a fresh virtual environment and run them from this folder.
- capture_scene.py
- csv_to_points.py
- 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 QGIS essentials part 1 (run by tools/qgis-capture/scene_shot.ps1).
1. Opens Data Source Manager > Delimited Text with the Environment Agency rainfall gauge CSV, X field = long, Y field = lat, CRS EPSG:4326, and grabs the dialogue.2. Adds the gauges (saved to GeoPackage by csv_to_points.py) over OpenStreetMap and grabs the map.Inputs are read from C:\\TechnicalGIS\\qgis-work\\csv-to-points so no personal path appears."""from qgis.core import (QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsMarkerSymbol, QgsProject, QgsRasterLayer, QgsRectangle, QgsVectorLayer)from qgis.PyQt.QtWidgets import QApplication, QComboBox, QGroupBox, QTableWidget, QDockWidget, QRadioButton, QWidget
WORK = r"C:\TechnicalGIS\qgis-work\csv-to-points"
def steps(iface, shot, log): st = {}
def setup(): mw = iface.mainWindow() mw.showNormal() mw.resize(1500, 900) mw.move(40, 40) for dock in mw.findChildren(QDockWidget): if dock.objectName() != "Layers": dock.hide() QgsProject.instance().setCrs(QgsCoordinateReferenceSystem("EPSG:3857")) log("setup")
def open_dsm(): iface.openDataSourceManagerPage("delimitedtext")
def fill(): dsm = next(w for w in QApplication.topLevelWidgets() if w.metaObject().className() == "QgsDataSourceManagerDialog") dsm.show() dsm.raise_() dsm.resize(1100, 820) st["dsm"] = dsm page = next(w for w in dsm.findChildren(QWidget) if w.metaObject().className() == "QgsDelimitedTextSourceSelect") st["page"] = page fw = next(w for w in page.findChildren(QWidget) if w.metaObject().className() == "QgsFileWidget") fw.setFilePath(WORK + r"\rainfall-stations.csv") log("file set; radios: " + ", ".join(r.objectName() for r in page.findChildren(QRadioButton)))
def fields(): page = st["page"] combos = {c.objectName(): c for c in page.findChildren(QComboBox)} log("combos: " + ", ".join(sorted(combos))) for name, value in (("cmbXField", "long"), ("cmbYField", "lat")): c = combos[name] c.setCurrentIndex(c.findText(value)) crs = next((w for w in page.findChildren(QWidget) if w.metaObject().className() == "QgsProjectionSelectionWidget"), None) if crs: crs.setCrs(QgsCoordinateReferenceSystem("EPSG:4326")) # QgsCollapsibleGroupBox comes back as a plain QGroupBox, so use its Qt property. for gb in page.findChildren(QGroupBox): if gb.metaObject().className() == "QgsCollapsibleGroupBox": gb.setProperty("collapsed", gb.objectName() not in ("geometryDefinitionGroupBox", "fileFormatGroupBox")) table = page.findChild(QTableWidget, "tblSample") if table: heads = [table.horizontalHeaderItem(i).text() for i in range(table.columnCount())] if "lat" in heads: table.scrollToItem(table.item(0, heads.index("long")), QTableWidget.PositionAtCenter) log(f"sample columns: {len(heads)}") log(f"x={combos['cmbXField'].currentText()} y={combos['cmbYField'].currentText()}")
def grab_dialog(): shot(st["dsm"], "01-qgis-delimited-text-dialog.png") st["dsm"].close()
def add_layers(): project = QgsProject.instance() osm = QgsRasterLayer("type=xyz&url=https://tile.openstreetmap.org/{z}/{x}/{y}.png&zmax=19&zmin=0", "OpenStreetMap", "wms") gauges = QgsVectorLayer(WORK + r"\rainfall-gauges.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"})) project.addMapLayer(osm) project.addMapLayer(gauges) canvas = iface.mapCanvas() canvas.setDestinationCrs(project.crs()) tr = QgsCoordinateTransform(QgsCoordinateReferenceSystem("EPSG:4326"), project.crs(), project) canvas.setExtent(tr.transformBoundingBox(QgsRectangle(-6.2, 49.9, 2.3, 55.9))) canvas.refresh() log(f"gauges valid={gauges.isValid()} n={gauges.featureCount()}")
def grab_map(): shot(iface.mainWindow(), "02-qgis-rainfall-gauges-map.png")
return [ (500, setup), (1000, open_dsm), (2500, fill), (3000, fields), (2000, grab_dialog), (500, add_layers), (15000, grab_map), ]csv_to_points.py
"""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 csvimport mathimport sysimport urllib.requestfrom pathlib import Path
from qgis.core import (QgsApplication, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsMarkerSymbol, QgsProject, QgsRasterLayer, QgsVectorFileWriter, QgsVectorLayer)
HERE = Path(__file__).resolve().parentDATA = 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: E402from 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, errsaved = 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()