"""Find and download Environment Agency LiDAR tiles from Defra Survey Data Download. Uses the same search service as the map at https://environment.data.gov.uk/survey: POST a GeoJSON polygon (WGS84 longitude/latitude) and get back every tile, product, year and resolution that intersects it. Each result has a direct zip download link. Examples: python defra_survey_download.py --bbox -2.478 50.690 -2.460 50.698 --list python defra_survey_download.py --bbox -2.478 50.690 -2.460 50.698 \ --product lidar_composite_dtm --resolution 1 --out data Standard library only. Data: Environment Agency, Open Government Licence v3.0. """ from __future__ import annotations import argparse import json import sys import urllib.request import zipfile from pathlib import Path SEARCH_URL = "https://environment.data.gov.uk/tiles/collections/survey/search" def search(bbox: tuple[float, float, float, float]) -> list[dict]: """Every survey product that intersects a lon/lat bounding box.""" w, s, e, n = bbox polygon = {"type": "Polygon", "coordinates": [[[w, s], [e, s], [e, n], [w, n], [w, s]]]} req = urllib.request.Request( SEARCH_URL, data=json.dumps(polygon).encode(), # The service only accepts the GeoJSON media type; plain application/json is rejected. headers={"Content-Type": "application/geo+json", "User-Agent": "technicalgis-tutorial"}, method="POST", ) with urllib.request.urlopen(req, timeout=60) as r: return json.load(r)["results"] def download(uri: str, out_dir: Path) -> Path: """Download one tile zip (it can take a minute while the server prepares it) and unzip it.""" out_dir.mkdir(parents=True, exist_ok=True) req = urllib.request.Request(uri, headers={"User-Agent": "technicalgis-tutorial"}) with urllib.request.urlopen(req, timeout=600) as r: name = r.headers.get_filename() or uri.rstrip("/").replace("/", "-") + ".zip" path = out_dir / name with open(path, "wb") as f: while chunk := r.read(1 << 20): f.write(chunk) with zipfile.ZipFile(path) as z: z.extractall(out_dir / path.stem) names = z.namelist() print(f" {path.name}: {path.stat().st_size / 1e6:.0f} MB") for n in names: print(f" {n}") return out_dir / path.stem def main() -> None: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--bbox", nargs=4, type=float, required=True, metavar=("WEST", "SOUTH", "EAST", "NORTH")) p.add_argument("--list", action="store_true", help="list what is available and stop") p.add_argument("--product", default="lidar_composite_dtm", help="product id, e.g. national_lidar_programme_point_cloud") p.add_argument("--year", help="survey year; default is the latest available") p.add_argument("--resolution", default="1", help="resolution in metres, e.g. 1, 2 or 0.5 (ignored for point clouds)") p.add_argument("--out", type=Path, default=Path("data")) a = p.parse_args() results = search(tuple(a.bbox)) if a.list: print(f"{len(results)} products for this area") for r in results: print(f" {r['product']['id']:<42} {r['year']['label']} {r['resolution']['label']:<5} {r['tile']['label']}") return picked = [r for r in results if r["product"]["id"] == a.product] if "point_cloud" not in a.product: picked = [r for r in picked if r["resolution"]["id"] == a.resolution] if not picked: sys.exit(f"No {a.product} tiles at {a.resolution} m here. Run with --list to see what there is.") year = a.year or max(r["year"]["id"] for r in picked) picked = [r for r in picked if r["year"]["id"] == year] print(f"Downloading {len(picked)} tile(s) of {picked[0]['product']['label']} {year}") for r in picked: download(r["uri"], a.out) if __name__ == "__main__": main()