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)")