03

Polygons

Where can we swim in the UK? AI-coded

#30DayMapChallenge prompt: A map challenge classic. Map with polygons.

England's and Scotland's lakes, reservoirs and wide rivers, lifted off the map and packed at the same scale (lakes of 5 ha or more, named ones from 1 ha, and any with a swim spot). Hover for names. Search by name, or click lakes to compare them side by side at the same scale (turned to lie flat, as in the pile, not north-up); the map above flies to the lake you click. · ⤢ full screen

⤓ Download the picture: every lake side by side (PNG)

Why this map

Where are we allowed to swim in the UK? Known outdoor swimming spots (reservoirs, quarries, ponds) are marked in the map in orange. There's a large contrast in size to how much open water there is: lakes, rivers, etc. The navigator below shows all these water bodies put together next to each other. I'd love to see more people having access to safe, clean open water swimming spots, these spaces are great for mental health, fitness and community!

Data sources

Outdoor swimming spots in OpenStreetMap (UK) ↗

From
OpenStreetMap contributors, downloaded via the Overpass API
What
192 places in the UK tagged for swimming: leisure=swimming_area (62), leisure=bathing_place (113) or a water body tagged sport=swimming (17). 83 have a shape (often the swim area rather than the whole lake, e.g. West Reservoir Centre and the three Hampstead Heath bathing ponds) and 109 are only a point. Only spots volunteers have tagged, so most places people swim are missing. Includes 1 paddling pool, 1 swimming pool and 9 spots tagged access=private. Converted from the Overpass response to GeoJSON by get_data.py, tags unchanged.
Time
Snapshot of OpenStreetMap at 3 Nov 2026, 19:57 UTC (spots added by volunteers over many years); downloaded 3 Nov 2026
Resolution
Outlines and points drawn by volunteers from aerial imagery, GPS or local knowledge, so approximate (typically a few metres off). Only 7 of the 192 say how they were mapped (source=). A point marks a spot on the bank or in the water, not the area you swim in.
Licence
ODbL, © OpenStreetMap contributors

Scotland's designated bathing waters (official extents) ↗

From
Scottish Environment Protection Agency (SEPA)
What
90 polygons, one per designated bathing water in Scotland: 'Extents of bathing waters defined by The Scottish Government and SEPA' under the Bathing Waters Directive. Mostly sea beaches; inland ones include Loch Morlich, Luss Bay (Loch Lomond) and Dores (Loch Ness). Includes the latest water-quality class. Only officially designated sites; most places people swim in Scotland are not designated.
Time
Sites designated 1987–2026; file last changed 19 May 2026; downloaded 3 Nov 2026
Resolution
Official extents drawn by SEPA, 0.8 to 260 hectares each, in British National Grid coordinates (EPSG:27700)
Licence
Open Government Licence v3.0 (SEPA: 'This data is delivered under the terms of the Open Government Licence'). Credit: Contains public sector information licensed under the Open Government Licence v3.0 (SEPA)

Northern Ireland's designated bathing waters (bathing water areas) ↗

From
Department of Agriculture, Environment and Rural Affairs (DAERA), Marine and Fisheries Division
What
33 polygons, one per designated bathing water in Northern Ireland: 32 on the coast and 1 inland (Rea's Wood, Lough Neagh, designated 2025). DAERA: the areas 'are defined by the land parcel lines at the upper edge of the beach and extend approx. 200m seaward into the bathing water area', so each shape is beach plus a strip of sea, not a measured swim area.
Time
Sites designated 1988–2025; DAERA updated the data in May 2025 (7 new sites), last edit 18 Jun 2025; downloaded 3 Nov 2026
Resolution
Drawn by DAERA on the OSNI 1:10,000 raster basemap; the seaward edge is approximate (~200 m). Coordinates are Web Mercator (EPSG:3857), not the usual lat/lon.
Licence
Open Government Licence v3.0. Credit: contains Ordnance Survey of Northern Ireland information licensed under the Open Government Licence v3.0 (DAERA)

England's designated bathing waters (sampling points) ↗

From
Environment Agency
What
489 points where the Environment Agency samples water, one per bathing water: 464 currently designated (373 coastal, 53 estuary ('transitional'), 20 river, 18 lake, including the three Hampstead Heath ponds and the Serpentine) and 25 no longer designated (notes = 'De-designated'). Points, not swim areas. West Reservoir, and most places people swim, are not designated.
Time
Sites designated 1988–2026, water-quality classes up to 2025; file updated 18 Sep 2026; downloaded 3 Nov 2026
Resolution
One sampling point per site, as a grid reference in British National Grid (EPSG:27700). Many are rounded: about 1 in 5 to the nearest 100 m and another third to the nearest 10 m.
Licence
Open Government Licence v3.0. Credit: © Environment Agency copyright and/or database right 2015. All rights reserved.

Wales's designated bathing waters (sampling points) ↗

From
Natural Resources Wales (Cyfoeth Naturiol Cymru), bathing-water API
What
114 sampling points, one per designated bathing water in Wales: 107 coastal, 3 estuary ('transitional'), 2 lake (Llanishen Reservoir, Llyn Padarn) and 2 river (Llandeilo Swing Bridge, The Warren at Hay-on-Wye). Points, not swim areas. Converted from the API's JSON to GeoJSON by get_data.py, keeping name, id, type, year designated and coordinates.
Time
Designations up to the 2026 season (newest: Fontygary Bay and Llandeilo Swing Bridge); downloaded 3 Nov 2026
Resolution
One sampling point per site, from the API's latitude/longitude; the API gives no accuracy
Licence
Open Government Licence v3.0 (NRW: the data 'is openly licensed under the Open Government Licence'). Credit: Contains public sector information licensed under the Open Government Licence v3.0 (Natural Resources Wales)

All water areas in OpenStreetMap (Great Britain, Ireland and Northern Ireland) ↗

From
OpenStreetMap contributors; extracts made by Geofabrik GmbH (UK page above, plus download.geofabrik.de/europe/ireland-and-northern-ireland.html)
What
Every water area in OpenStreetMap (layer gis_osm_water_a_free_1), saved unchanged as one GeoPackage per extract: England 195,191, Scotland 61,709, Wales 18,081, Ireland and Northern Ireland 40,903 (includes the Republic of Ireland). Type field fclass: water (lakes and ponds, many tiny), reservoir, riverbank (wide rivers drawn as areas), dock, and wetland_* classes (bog, marsh, tidal flat...) that aren't open water. Narrow rivers and the sea are not areas here. No swimming or access information, and the 'water' class can't tell a lake from a sewage lagoon or industrial basin, so a few of those are on the map too. On the map: only lakes and ponds, reservoirs and wide rivers; water outside the UK's coastline (the Republic of Ireland, and tidal estuaries and rivers, where different rules apply) left out; 5 hectares or bigger, plus smaller ones that hold a known swim spot: 7,129 areas. In the lifted picture (lifted.png): every one of them in England (177,792) and Scotland (54,410), whatever its size; in the zoomable version (lifted.html): 5,606 and 6,243 of them (5 ha or more, named ones from 1 ha, and any with a swim spot).
Time
OpenStreetMap data up to 2 Nov 2026, 21:21 UTC (Geofabrik extracts); downloaded 3 Nov 2026
Resolution
Shorelines drawn by volunteers, mostly from aerial imagery, so approximate (a few metres) and more detailed in some areas than others. Small ponds are patchy.
Licence
ODbL, © OpenStreetMap contributors

UK country boundaries (Countries, December 2024, BGC) ↗

From
Office for National Statistics (ONS)
What
4 polygons: England, Northern Ireland, Scotland, Wales (codes CTRY24CD, names CTRY24NM). For telling which nation's swimming rules apply. Clipped to the coastline, so estuaries and the sea fall outside every nation.
Time
Boundaries as at December 2024; layer last edited 11 Feb 2025; downloaded 3 Nov 2026
Resolution
ONS: 'Generalised (20m) - clipped to the coastline (Mean High Water mark)' ('BGC'); downloaded as latitude/longitude (EPSG:4326)
Licence
Open Government Licence v3.0. Credit: Source: Office for National Statistics licensed under the Open Government Licence v.3.0. Contains OS data © Crown copyright and database right 2025

How it was made

Pythonfoliumgeopandaspandas
See the code (map.py)
"""
Day 3 · Polygons
The prompt: A map challenge classic. Map with polygons.

What I'm mapping: Swimming spots in the UK
"""

from pathlib import Path

import folium
import geopandas as gpd
import pandas as pd      # you'll need pd.concat in a moment

from mapkit import palette as P
from mapkit.folium_style import (OSM_DATA_CREDIT, add_basemap, add_credit, add_legend, add_title,
                                 connect_to_extras, style_map)

HERE = Path(__file__).parent      # this day's folder
DATA = HERE / "data"              # put the data files you download in here
                                  # (get them all with: python days/03-polygons/get_data.py)

# Settings worth playing with (all distances in metres, areas in hectares: 1 ha = 100 m × 100 m)
MIN_HECTARES = 5       # lakes smaller than this are left out of the "could swim" layer...
                       # ...unless they hold a known swim spot (the Hampstead ponds are only 0.5–1.3 ha)
MATCH_METRES = 100     # a swim point this close to a lake counts as "in" it (England's points are rounded to 10–100 m)
BIG_HECTARES = 50      # on lakes bigger than this, and on rivers, a swim point isn't the whole lake...
SPOT_METRES = 250      # ...so show only this radius around the spot, cut to the water's edge
SIMPLIFY_METRES = 10   # smooth the outlines to this many metres, so map.html stays a sensible size


# ── STEP 1 · An empty map ─────────────────────────────────────────────────
# prefer_canvas=True draws all the shapes on one canvas instead of one SVG element each:
# with 7,000+ lakes that's the difference between smooth and sluggish.
m = folium.Map(location=[54.5, -3.5], zoom_start=6, tiles=None, prefer_canvas=True)
add_basemap(m, "light")           # background map: also "light-nolabels", "dark", "osm", "mapbox"
style_map(m)                      # the site's font + ink-outlined buttons


# ── STEP 2 · Load your data ───────────────────────────────────────────────

# 2a · Every water area in OpenStreetMap, one file per region.
#      where=... keeps lakes and ponds ("water"), reservoirs and wide rivers ("riverbank"),
#      and drops wetlands and docks while reading.
england = gpd.read_file(DATA / "osm_water_england.gpkg", where="fclass IN ('water', 'reservoir', 'riverbank')")
ireland_and_northern_ireland = gpd.read_file(DATA / "osm_water_ireland_and_northern_ireland.gpkg", where="fclass IN ('water', 'reservoir', 'riverbank')")
scotland = gpd.read_file(DATA / "osm_water_scotland.gpkg", where="fclass IN ('water', 'reservoir', 'riverbank')")
wales = gpd.read_file(DATA / "osm_water_wales.gpkg", where="fclass IN ('water', 'reservoir', 'riverbank')")

# Stack the four tables into one. Lakes on the England/Scotland/Wales borders are in
# two files, so keep each OpenStreetMap id only once.
water = pd.concat([england, scotland, wales, ireland_and_northern_ireland], ignore_index=True)
water = water.drop_duplicates("osm_id")

# Switch from latitude/longitude (EPSG:4326) to British National Grid (EPSG:27700),
# where coordinates are in metres, so areas and distances come out in real units.
water = water.to_crs(27700)
water["hectares"] = water.area / 10_000

# 2b · Which nation is each lake in? The law on swimming is different in Scotland.
#      Take a point that's guaranteed to be inside each lake, and ask which country it falls in.
countries = gpd.read_file(DATA / "ons_countries_dec2024_bgc.geojson").to_crs(27700)
countries = countries[["CTRY24NM", "geometry"]].rename(columns={"CTRY24NM": "nation"})
inside = gpd.sjoin(gpd.GeoDataFrame(geometry=water.representative_point()), countries,
                   how="left", predicate="within")
water["nation"] = inside["nation"]
# The country shapes stop at the high-water line, so water with no nation is either in the
# Republic of Ireland, or tidal (estuaries, tidal rivers), where different rules apply. Leave both out.
print(f"Water areas: {len(water):,}, of which {water['nation'].isna().sum():,} tidal or in the Republic (left out)")
water = water[water["nation"].notna()]

# 2c · The known swimming spots. Each file names things differently,
#      so give them all the same two columns: name and source.
swim = gpd.read_file(DATA / "osm_swim_spots.geojson").to_crs(27700)
swim = swim[~swim["leisure"].isin(["paddling_pool", "swimming_pool"])]   # not outdoor swimming
swim["source"] = "OpenStreetMap swim spot"

sepa = gpd.read_file(DATA / "scotland_sepa_bathing_water_polygons.gpkg",
                     columns=["description"]).to_crs(27700)   # only the column we need (its date column prints warnings)
sepa["name"] = sepa["description"]
sepa["source"] = "Official bathing water (SEPA)"

daera = gpd.read_file(DATA / "ni_daera_bathing_water_areas.geojson").to_crs(27700)  # this one is in EPSG:3857
daera["name"] = daera["Name"].str.title()                                             # "REA'S WOOD" → "Rea'S Wood"...
daera["name"] = daera["name"].str.replace("'S ", "'s ")                               # ...→ "Rea's Wood"
daera["source"] = "Official bathing water (DAERA): beach and ~200 m of sea"

ea = gpd.read_file(DATA / "england_ea_bathing_waters.geojson").to_crs(27700)
ea = ea[ea["notes"] == "Active"]                  # 25 sites are no longer designated
ea["name"] = ea["bw_name"]
ea["source"] = "Official bathing water (Environment Agency)"

nrw = gpd.read_file(DATA / "wales_nrw_bathing_waters.geojson").to_crs(27700)
nrw["source"] = "Official bathing water (Natural Resources Wales)"

cols = ["name", "source", "geometry"]
inland = ["Lake", "River"]
# Spots that already come as shapes: OpenStreetMap swim areas, Scotland's and Northern Ireland's bathing waters
outlines = pd.concat([swim[swim.geom_type != "Point"][cols], sepa[cols], daera[cols]], ignore_index=True)
# Spots that are only a point: OpenStreetMap points, and England's and Wales's inland bathing waters
points = pd.concat([swim[swim.geom_type == "Point"][cols],
                    ea[ea["bw_type"].isin(inland)][cols],
                    nrw[nrw["bw_type"].isin(inland)][cols]], ignore_index=True)
# England's and Wales's sea and estuary bathing waters: no water shape to draw, so they stay dots
sea_points = pd.concat([ea[~ea["bw_type"].isin(inland)][cols],
                        nrw[~nrw["bw_type"].isin(inland)][cols]], ignore_index=True)

# 2d · Turn swim points into shapes: find the lake or river each point is in (or within MATCH_METRES of).
#      First skip points that already have an outline nearby (e.g. the Hampstead ponds are in OSM
#      as swim areas AND in the Environment Agency list as points: keep the outline).
nearest_outline = gpd.sjoin_nearest(points, outlines[["geometry"]], how="left", max_distance=MATCH_METRES)
has_outline = nearest_outline["index_right"].notna().groupby(level=0).any()
points = points[~has_outline]

nearest_water = gpd.sjoin_nearest(points, water[["geometry"]], how="left", max_distance=MATCH_METRES)
nearest_water = nearest_water[~nearest_water.index.duplicated()]   # a point exactly between two lakes matches both
found = nearest_water[nearest_water["index_right"].notna()]
not_found = nearest_water[nearest_water["index_right"].isna()]

matched = []
lakes_used = set()
for _, point in found.iterrows():
    lake = water.loc[point["index_right"]]
    if lake["fclass"] == "riverbank" or lake["hectares"] > BIG_HECTARES:
        # A spot on Windermere isn't all of Windermere: keep the water within SPOT_METRES of the point.
        shape = lake.geometry.intersection(point.geometry.buffer(SPOT_METRES))
        how = f"{point['source']} (the water within {SPOT_METRES} m of the spot)"
    else:
        if point["index_right"] in lakes_used:      # two points in the same small pond: draw it once
            continue
        lakes_used.add(point["index_right"])
        shape = lake.geometry
        how = f"{point['source']} (the whole pond or lake it's in)"
    matched.append({"name": point["name"] if pd.notna(point["name"]) else lake["name"],
                    "source": how, "geometry": shape})
matched = gpd.GeoDataFrame(matched, crs=27700)

spots = pd.concat([outlines, matched], ignore_index=True)
spots["name"] = spots["name"].fillna("Unnamed swimming spot")
# Which lake is each spot on? (Clicking a spot on the map then picks its lake in the lifted piles.)
on_lake = gpd.sjoin(spots[["geometry"]], water[["osm_id", "geometry"]], how="left", predicate="intersects")
spots["lake_osm_id"] = on_lake.groupby(level=0)["osm_id"].first().fillna("")
print(f"Swim spots with a shape: {len(outlines)} outlines + {len(matched)} found in a lake or river")
print(f"Swim spots that stay dots: {len(sea_points)} sea bathing waters + {len(not_found)} with no water nearby")

# At country scale a pond is smaller than a pixel, so every shape also gets a dot (to find it),
# alongside the sea bathing waters, which only ever were points.
shape_dots = spots[cols + ["lake_osm_id"]].copy()
shape_dots["geometry"] = spots.representative_point()
dots = pd.concat([shape_dots, sea_points], ignore_index=True)
dots["name"] = dots["name"].fillna("Unnamed swimming spot")
dots["lake_osm_id"] = dots["lake_osm_id"].fillna("")      # sea bathing waters aren't on a lake

# The spots with no lake or river outline within MATCH_METRES get their own layer, so they're easy
# to find and check (often a tidal rock pool, a beach, or a river drawn only as a line).
no_water = not_found[cols].copy()
no_water["name"] = no_water["name"].fillna("Unnamed swimming spot")
no_water["why"] = f"No lake or river outline within {MATCH_METRES} m in OpenStreetMap"

# 2e · The "could swim here" layer: lakes of MIN_HECTARES or more, plus any smaller one that holds a known spot.
holds_spot = gpd.sjoin(water[["geometry"]], spots[["geometry"]], predicate="intersects").index
water = water[(water["hectares"] >= MIN_HECTARES) | water.index.isin(holds_spot)]
print(f"Water in the 'could swim' layer: {len(water):,}", water["nation"].value_counts().to_dict())


# ── STEP 3 · Colours and words ────────────────────────────────────────────
# One colour per legal situation (inland water only), and one for known swim spots on top.
SPOT_COLOUR = P.TANGERINE
CHECK_COLOUR = P.SUNFLOWER          # swim spots with no water outline nearby
NATION_COLOUR = {"Scotland": P.TEAL_GREEN,
                 "England": P.COBALT, "Wales": P.COBALT, "Northern Ireland": P.COBALT}
# What the law says. Scotland's line is quoted word for word; the others are summarised from
# Countryside and Rights of Way Act 2000 Sch. 2 (England), Welsh Government 2019 (Wales) and nidirect (NI).
RULE = {
    "Scotland": "Scotland: access rights extend to swimming (subject to any local byelaws)",
    "England": "England: no general right to bathe in non-tidal water",
    "Wales": "Wales: no general public right of access to inland water",
    "Northern Ireland": "Northern Ireland: no general public right to swim",
}
KIND = {"water": "Lake or pond", "reservoir": "Reservoir", "riverbank": "River (wide stretch)"}

water["name"] = water["name"].fillna("Unnamed")
water["kind"] = water["fclass"].map(KIND) + " · " + water["hectares"].round(1).astype(str) + " ha"
water["rule"] = water["nation"].map(RULE)


# ── STEP 4 · Put the data on the map (with tooltips) ─────────────────────
def for_the_web(gdf, columns):
    """Smooth the outlines, go back to latitude/longitude, and round to ~1 m (5 decimals).
    Without the rounding, every coordinate is written with 15 decimals and map.html triples in size."""
    gdf = gdf[columns].copy()
    gdf["geometry"] = gdf.geometry.simplify(SIMPLIFY_METRES)
    gdf = gdf.to_crs(4326)
    gdf["geometry"] = gdf.geometry.set_precision(0.00001)
    return gdf[~gdf.geometry.is_empty]

# A FeatureGroup is a layer you can switch on and off. Shapes go into the group, the group goes on the map.
could_swim = folium.FeatureGroup(name="Water where swimming could be allowed").add_to(m)
folium.GeoJson(
    for_the_web(water, ["name", "kind", "rule", "nation", "osm_id", "geometry"]),   # osm_id: see STEP 5
    style_function=lambda feature: {           # runs once per lake: colour it by nation
        "fillColor": NATION_COLOUR[feature["properties"]["nation"]],
        "fillOpacity": 0.55,
        "color": NATION_COLOUR[feature["properties"]["nation"]],
        "weight": 0.5,
    },
    tooltip=folium.GeoJsonTooltip(fields=["name", "kind", "rule"], labels=False),
).add_to(could_swim)

known = folium.FeatureGroup(name="Known swimming spots: outlines").add_to(m)   # added later, so it draws on top
folium.GeoJson(
    for_the_web(spots, ["name", "source", "lake_osm_id", "geometry"]),
    style_function=lambda feature: {"fillColor": SPOT_COLOUR, "fillOpacity": 0.9, "color": P.INK, "weight": 1},
    tooltip=folium.GeoJsonTooltip(fields=["name", "source"], labels=False),
).add_to(known)

# The dots get their own switch: untick it for a polygons-only map.
spot_dots = folium.FeatureGroup(name="Known swimming spots: dots (and sea bathing waters)").add_to(m)
folium.GeoJson(
    for_the_web(dots, ["name", "source", "lake_osm_id", "geometry"]),
    marker=folium.CircleMarker(radius=3.5),    # points are drawn as small circles
    style_function=lambda feature: {"fill": True,   # circles aren't filled unless you say so
                                    "fillColor": SPOT_COLOUR, "fillOpacity": 0.9, "color": P.INK, "weight": 0.8},
    tooltip=folium.GeoJsonTooltip(fields=["name", "source"], labels=False),
).add_to(spot_dots)

# The spots with no water outline nearby: bigger yellow circles, on top of everything, to go and look at.
check = folium.FeatureGroup(name=f"Swim spots with no water outline nearby ({len(no_water)})").add_to(m)
folium.GeoJson(
    for_the_web(no_water, ["name", "source", "why", "geometry"]),
    marker=folium.CircleMarker(radius=7),
    style_function=lambda feature: {"fill": True, "fillColor": CHECK_COLOUR, "fillOpacity": 1,
                                    "color": P.INK, "weight": 2},
    tooltip=folium.GeoJsonTooltip(fields=["name", "source", "why"], labels=False),
).add_to(check)


# ── STEP 5 · Switches ─────────────────────────────────────────────────────
# LayerControl is the box (top right) with a tick box for each FeatureGroup. Add it last.
folium.LayerControl(collapsed=False).add_to(m)
# Link this map with the lifted piles under it on the day page (lifted.html), both ways:
# click a lake there and this map flies to it; click a lake (or a swim spot on one) here, or find
# it with the search box, and the piles pick the same lake. They match lakes by osm_id.
connect_to_extras(m, search="Find a lake or swim spot")


# ── STEP 6 · A title, a legend and credits ────────────────────────────────
add_title(m, "Swimming spots in the UK",
          f"Known outdoor swimming spots, and every lake, reservoir and wide river of {MIN_HECTARES} ha or more in OpenStreetMap, "
          "coloured by whether the law gives a right to swim there. Inland water only. "
          "'Could' doesn't mean safe, clean, or allowed at a particular spot.")
add_legend(m, "Swimming", {
    "Known swimming spot (zoom in for its outline, if it has one)": SPOT_COLOUR,
    f"Swim spot with no water outline within {MATCH_METRES} m": CHECK_COLOUR,
    "Scotland: access rights include swimming": NATION_COLOUR["Scotland"],
    "England, Wales, N. Ireland: no general right to swim": NATION_COLOUR["England"],
}, shape="square")
add_credit(m, OSM_DATA_CREDIT
           + " · Bathing waters: SEPA; DAERA (contains OSNI information); © Environment Agency copyright"
             " and/or database right 2015. All rights reserved; Natural Resources Wales (all OGL v3)"
           + " · Boundaries: Source: Office for National Statistics licensed under the OGL v3."
             " Contains OS data © Crown copyright and database right 2025")


# ── Save ──────────────────────────────────────────────────────────────────
m.save(HERE / "map.html")
print("Saved", HERE / "map.html", f"({(HERE / 'map.html').stat().st_size / 1e6:.1f} MB)")

Doing the challenge too? Use this template for your own →