2 Commits
12051 changed files with 186 additions and 32498 deletions
+62
View File
@@ -0,0 +1,62 @@
# Streamlined deploy pipeline for Gitea -> Coolify.
# Copy to .gitea/workflows/deploy.yml in a repo and fill in the env block.
name: Deploy
on:
push:
branches: [main]
workflow_dispatch:
concurrency:
group: deploy
cancel-in-progress: false
jobs:
deploy:
runs-on: [self-hosted, linux]
timeout-minutes: 30
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build and test
run: |
echo "build step placeholder"
- name: Trigger Coolify deploy
env:
COOLIFY_TOKEN: $(cat /root/.config/coolify_api_token)
COOLIFY_URL: http://192.168.178.132:8000
COOLIFY_APP_UUID: 1334ce19-40f9-455c-9930-bef2e59558ac
run: |
curl -sS -X POST \
"${COOLIFY_URL}/api/v1/deploy?uuid=${COOLIFY_APP_UUID}&force=true" \
-H "Authorization: Bearer ${COOLIFY_TOKEN}" \
-w "\nHTTP %{http_code}\n" \
-o /tmp/deploy.json
cat /tmp/deploy.json
grep -q 'deployment_uuid\|"status":true' /tmp/deploy.json || { echo "::error::Coolify deploy trigger failed"; exit 1; }
- name: Verify live site
env:
LIVE_URL: https://laadpalen.laserraptorai.duckdns.org
run: |
set +e
ok=no
for i in $(seq 1 24); do
code=$(curl -s -o /dev/null -m 30 -w '%{http_code}' "${LIVE_URL}/")
echo "attempt $i: HTTP $code"
[ "$code" = "200" ] && { ok=yes; break; }
sleep 5
done
if [ "$ok" != "yes" ]; then
echo "::error::live site did not return 200"
exit 1
fi
echo "deploy verified: ${LIVE_URL}"
- name: Alert on failure
if: failure()
run: |
echo "DEPLOY FAILED" >&2
@@ -1,50 +0,0 @@
name: Hourly charging snapshot
on:
schedule:
# Every hour at minute 5 (UTC). Snapshots are bucketed by Europe/Amsterdam time.
- cron: '5 * * * *'
workflow_dispatch: # allow manual runs
permissions:
contents: write
concurrency:
group: charging-snapshot
cancel-in-progress: false
jobs:
snapshot:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Set up Node
uses: actions/setup-node@v5
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: data-pipeline/package-lock.json
- name: Install dependencies
working-directory: data-pipeline
run: npm ci
- name: Fetch snapshot (NDW OCPI -> occupancy + status)
working-directory: data-pipeline
run: npm run snapshot
- name: Commit and push
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add webapp/public/data/snapshots webapp/public/data/status
if git diff --staged --quiet; then
echo "No changes to commit"
exit 0
fi
TS=$(date -u +"%Y-%m-%d %H:%M UTC")
git commit -m "data: charging snapshot ${TS}"
git push
+1 -3
View File
@@ -1,3 +1 @@
node_modules/
.DS_Store
*.log
__pycache__/
+6 -7
View File
@@ -1,8 +1,7 @@
FROM node:20-alpine
FROM python:3.12-slim
WORKDIR /app
COPY webapp/package*.json ./
RUN npm ci
COPY webapp/ .
RUN npm run build
EXPOSE 3000
CMD ["npm", "run", "start"]
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 RobbertJ
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-58
View File
@@ -1,58 +0,0 @@
# Laadpalenviewer
Interactieve kaart van laadpunten in Nederland, met twee lagen:
- **Personenauto** — alle publiek toegankelijke laadpunten (NDW DOT-NL OCPI), gekleurd op
OCPI-status (beschikbaar / bezet / niet beschikbaar / onbekend).
- **Logistiek / vracht** — zware-voertuig- en megawatt-laadpunten (Milence, WattHub, MCS,
DC ≥ 350 kW), samengevoegd uit NDW-classificatie + externe bronnen.
Plus gemeente- en provinciegrenzen (PDOK/CBS) en een per-gemeente "uitsnede" zoals de
Pakketpuntenviewer. Op landelijk niveau laden alle punten zonder details; bij het kiezen van
een gemeente worden alle details (laadpunten, connectoren, tarieven) direct geladen.
## Structuur
```
data-pipeline/ Node/TS generatiestap -> schrijft statische JSON/GeoJSON naar webapp/public/data
webapp/ Next.js 16 + React 19 + deck.gl + MapLibre (statisch te hosten, bv. Vercel)
```
## Databronnen
- NDW OCPI: `https://opendata.ndw.nu/charging_point_locations_ocpi.json.gz` (+ tariffs)
- PDOK CBS Gebiedsindelingen WFS (gemeente_gegeneraliseerd / provincie_gegeneraliseerd)
- Open Charge Map API (vrije `OCM_API_KEY`), EAFO (optionele statische export), curated hubs
## Data genereren
```bash
cd data-pipeline
npm install
# optioneel: export OCM_API_KEY=... en export BOUNDARY_YEAR=2025
npm run generate # gebruikt cache in .cache/
npm run generate:nocache # forceert verse downloads (--refresh)
```
Dit schrijft naar `webapp/public/`:
- `data/gemeenten/<slug>.geojson` — per-gemeente uitsnede (punten zonder details + grens)
- `data/gemeenten/<slug>.details.json` — per-gemeente detailbundel (volledige OCPI EVSE/connector/tarief)
- `data/nederland-passenger.geojson` / `data/nederland-freight.geojson` — landelijk, alle punten, geen details
- `data/provinces.geojson` — provinciegrenzen
- `municipalities.json` — gemeentelijst met tellingen
## Webapp draaien
```bash
cd webapp
npm install
npm run dev # http://localhost:3000
npm run build # statische productiebuild (roept de pipeline NIET aan)
```
## Classificatie afstellen
De vracht/personenauto-grens staat in één constante: `data-pipeline/src/classifyFreight.ts`
(`THRESHOLDS`). Verlaag `FREIGHT_DC_WATTS` voor meer recall, verhoog voor meer precisie.
Bekende truckhubs staan in `data-pipeline/data/curated-hubs.json`.
-5
View File
@@ -1,5 +0,0 @@
.venv/
.cache/
data/
__pycache__/
*.pyc
-27
View File
@@ -1,27 +0,0 @@
# Laadpalenviewer — analysis (golden dataset)
Python layer that integrates open Dutch datasets into a "golden dataset" and
exports derived map layers consumed by the webapp. Phase 1 works at **gemeente
grain**; buurt/PC4 grain and more sources (BAG/BGT, NDW traffic, grid) follow.
## Sources (open tier)
- **CBS Kerncijfers wijken en buurten** `85984NED` (CC-BY) — demographics, income,
urbanisation, car ownership. Field keys live in `src/ingest/cbs.py`.
- **Charger supply/usage** — our own `webapp/public/data` (municipalities.json,
crop-out GeoJSONs, hourly snapshots).
- **PDOK CBS Gebiedsindelingen** — gemeente polygons for the choropleth.
## Run
```bash
cd analysis
python3 -m venv .venv && ./.venv/bin/pip install -r requirements.txt
./.venv/bin/python -m src.main # uses caches in .cache/
./.venv/bin/python -m src.main --refresh # re-fetch CBS/PDOK
```
Outputs:
- `data/gold_gemeente.{csv,parquet}` — the golden dataset (gitignored).
- `webapp/public/data/derived/gemeente-metrics.geojson` — choropleth layer (committed).
- `webapp/public/data/derived/metrics-meta.json` — metric list for the viewer.
The viewer's **Analyse (per gemeente)** switcher (national view) renders any metric
as a choropleth. Attribution: data © CBS (CC-BY), PDOK, NDW.
-5
View File
@@ -1,5 +0,0 @@
requests>=2.31
pandas>=2.2
pyarrow>=16
numpy>=1.26
scikit-learn>=1.4
View File
-87
View File
@@ -1,87 +0,0 @@
"""Export the golden dataset + models as a viewer choropleth layer + metadata."""
from __future__ import annotations
import json
import math
import pandas as pd
from .ingest.boundaries import fetch_gemeente_geojson
from .paths import DERIVED_DIR
# Choropleth-selectable metrics (order = display order). category groups the switcher.
METRICS = [
{"key": "chargers_per_1000_inw", "label": "Laadpunten per 1.000 inwoners", "unit": "", "decimals": 1, "category": "Aanbod",
"desc": "Aantal OCPI-laadlocaties (NDW) gedeeld door inwoners (CBS) × 1.000. Maat voor dekking."},
{"key": "chargers_per_1000_auto", "label": "Laadpunten per 1.000 auto's", "unit": "", "decimals": 1, "category": "Aanbod",
"desc": "Laadlocaties per 1.000 personenauto's (CBS autobezit). Dekking t.o.v. het wagenpark."},
{"key": "chargers_total", "label": "Laadpunten totaal", "unit": "", "decimals": 0, "category": "Aanbod",
"desc": "Totaal aantal OCPI-laadlocaties (personen + vracht) in de gemeente."},
{"key": "power_per_1000_inw_kw", "label": "Vermogen per 1.000 inw.", "unit": "kW", "decimals": 0, "category": "Aanbod",
"desc": "Som van het max. connectorvermogen per 1.000 inwoners (personen + vracht). Vermogen afgeleid uit spanning × stroomsterkte waar NDW het niet rapporteert."},
{"key": "chargers_freight", "label": "Truck-laadlocaties", "unit": "", "decimals": 0, "category": "Logistiek",
"desc": "Locaties voor truckladen: dedicated voorzieningen (truck-operator, 'truck' in naam, MCS, logistiek depot) plus truck-capable snelladers (≥350 kW DC)."},
{"key": "freight_dedicated", "label": "Dedicated truck-locaties", "unit": "", "decimals": 0, "category": "Logistiek",
"desc": "Locaties met een expliciet trucksignaal: exploitant (Milence/WattHub), 'truck' in de naam, MCS-aansluiting, logistiek depot met ≥150 kW DC, of gecureerde hub. Exclusief locaties die alleen op vermogen kwalificeren."},
{"key": "freight_power_kw", "label": "Truck-laadvermogen", "unit": "kW", "decimals": 0, "category": "Logistiek",
"desc": "Som van het max. connectorvermogen van truck-laadlocaties in de gemeente. Indicatie van logistieke laadcapaciteit (bays per site niet meegenomen)."},
{"key": "avg_occupancy", "label": "Gem. bezetting (snapshot)", "unit": "%", "decimals": 1, "category": "Gebruik",
"desc": "Gemiddeld aandeel connectoren dat 'laadt' over de geregistreerde snapshot-uren."},
{"key": "price_kwh_median", "label": "Mediaan tarief (€/kWh)", "unit": "€/kWh", "decimals": 3, "category": "Prijs",
"desc": "Mediaan van het actuele energietarief (€/kWh) uit de OCPI-tarieven (NDW) over laadlocaties met een gepubliceerde prijs. ±50% van de connectoren publiceert geen tarief; momentopname uit de laatste data-update."},
{"key": "demand_per_1000_inw", "label": "Verwacht aanbod (peer-model)", "unit": "/1.000 inw", "decimals": 1, "category": "Vraag",
"desc": "Door een random-forest voorspeld aantal laadpunten o.b.v. demografie, per 1.000 inwoners. Peer-benchmark van het aanbod, geen gemeten vraag."},
{"key": "supply_gap", "label": "Afwijking t.o.v. peers", "unit": "laadpunten", "decimals": 0, "category": "Vraag",
"desc": "Werkelijk − verwacht (peer-model) aantal laadpunten. Negatief = minder aanbod dan demografisch vergelijkbare gemeenten. Gemodelleerd; NDW-dekkingsgaten (bijv. Amsterdam) kleuren dit beeld."},
{"key": "siting_priority", "label": "Plaatsingsprioriteit (0-100)", "unit": "", "decimals": 0, "category": "Siting",
"desc": "Prioriteit voor bijplaatsen: combineert relatief + absoluut tekort en huidige bezetting. Hoger = meer behoefte."},
{"key": "load_per_1000_inw_kw", "label": "Gesch. piekbelasting /1.000 inw", "unit": "kW", "decimals": 1, "category": "Congestie",
"desc": "Gemodelleerde potentiële piek ((personen-EVSE's × ~11 kW + truck-locaties × ~150 kW) × 30%) per 1.000 inwoners. Vermogens aangenomen."},
{"key": "congestion_index", "label": "Congestie-index (relatief)", "unit": "", "decimals": 0, "category": "Congestie",
"desc": "Relatieve percentielrang (0-100) van de piekbelasting per inwoner. NB: geen DSO-capaciteit ingelezen."},
{"key": "autos_per_huishouden", "label": "Auto's per huishouden", "unit": "", "decimals": 2, "category": "Demografie",
"desc": "CBS: personenauto's per huishouden — driver van laadbehoefte."},
{"key": "inkomen_per_inwoner", "label": "Gem. inkomen per inwoner", "unit": "×€1.000", "decimals": 1, "category": "Demografie",
"desc": "CBS gemiddeld inkomen per inwoner (×€1.000)."},
{"key": "stedelijkheid", "label": "Stedelijkheid (1=zeer sterk)", "unit": "", "decimals": 0, "category": "Demografie",
"desc": "CBS stedelijkheidsklasse 1 (zeer sterk stedelijk) t/m 5 (niet stedelijk)."},
]
# Extra fields carried in properties for the gemeente scorecard panel.
SCORECARD_COLS = [
"expected_chargers", "chargers_passenger", "inwoners", "autos_totaal",
"est_peak_load_kw", "potential_peak_load_kw", "live_peak_load_kw",
"evse_total", "charging_now", "occupancy_now",
"megawatt_sites", "supply_pct", "occupancy_pct", "gap_pct",
"price_kwh_mean", "price_kwh_n", "price_pct", "freight_pct",
]
EXPORT_COLS = [m["key"] for m in METRICS] + SCORECARD_COLS
def _clean(v):
if v is None or (isinstance(v, float) and (math.isnan(v) or math.isinf(v))):
return None
return v
def export_layer(gold: pd.DataFrame) -> None:
print("Exporting derived viewer layer...")
fc = fetch_gemeente_geojson()
by_code = {c: gold.loc[c] for c in gold.index}
for feat in fc["features"]:
code = feat["properties"].get("statcode")
props = {"code": code, "gemeente": feat["properties"].get("statnaam")}
row = by_code.get(code)
if row is not None:
props["slug"] = row.get("slug")
for col in EXPORT_COLS:
val = row.get(col)
props[col] = _clean(float(val)) if pd.notna(val) else None
feat["properties"] = props
meta = {"metrics": METRICS, "model": gold.attrs.get("model_metrics", {})}
fc["metadata"] = meta
DERIVED_DIR.mkdir(parents=True, exist_ok=True)
(DERIVED_DIR / "gemeente-metrics.geojson").write_text(json.dumps(fc))
(DERIVED_DIR / "metrics-meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2))
n = sum(1 for f in fc["features"] if f["properties"].get("chargers_total") is not None)
print(f" wrote gemeente-metrics.geojson ({n}/{len(fc['features'])} gemeenten with data)")
-38
View File
@@ -1,38 +0,0 @@
"""Assemble the gemeente-grain golden dataset and derived metrics."""
from __future__ import annotations
import pandas as pd
from .ingest.cbs import fetch_cbs_gemeente
from .ingest.chargers import fetch_chargers
from .models import add_models
from .paths import GOLD_DIR
def build_gold(refresh: bool = False) -> pd.DataFrame:
print("Building golden dataset (gemeente grain)...")
chargers = fetch_chargers()
cbs = fetch_cbs_gemeente(refresh=refresh)
df = chargers.join(cbs, how="left")
df["chargers_total"] = df["chargers_passenger"] + df["chargers_freight"]
# Prefer CBS population; fall back to municipalities.json population.
pop = df["inwoners"].fillna(df["population"]).replace(0, pd.NA)
autos = df["autos_totaal"].replace(0, pd.NA)
df["chargers_per_1000_inw"] = (df["chargers_total"] / pop * 1000).round(2)
df["chargers_per_1000_auto"] = (df["chargers_total"] / autos * 1000).round(2)
df["autos_per_charger"] = (autos / df["chargers_total"].replace(0, pd.NA)).round(1)
df["power_per_1000_inw_kw"] = (df["total_power_kw"] / pop * 1000).round(1)
# Phases 2-5 models (demand, siting, congestion/net-impact, municipal).
df = add_models(df)
GOLD_DIR.mkdir(parents=True, exist_ok=True)
df.to_csv(GOLD_DIR / "gold_gemeente.csv")
try:
df.to_parquet(GOLD_DIR / "gold_gemeente.parquet")
except Exception as e: # pyarrow missing -> CSV still written
print(f" (parquet skipped: {e})")
print(f" golden dataset: {len(df)} gemeenten, {df.shape[1]} columns")
return df
View File
-30
View File
@@ -1,30 +0,0 @@
"""Gemeente polygons (PDOK CBS Gebiedsindelingen WFS, GeoJSON, EPSG:4326)."""
from __future__ import annotations
import json
import requests
from ..paths import CACHE_DIR
YEAR = "2025"
WFS = f"https://service.pdok.nl/cbs/gebiedsindelingen/{YEAR}/wfs/v1_0"
def fetch_gemeente_geojson(refresh: bool = False) -> dict:
cache = CACHE_DIR / f"gemeenten_{YEAR}.geojson"
if cache.exists() and not refresh:
return json.loads(cache.read_text())
params = {
"service": "WFS",
"version": "2.0.0",
"request": "GetFeature",
"typeName": "gebiedsindelingen:gemeente_gegeneraliseerd",
"outputFormat": "application/json",
"srsName": "EPSG:4326",
"count": "1000",
"startIndex": "0",
}
r = requests.get(WFS, params=params, headers={"Accept": "application/json"}, timeout=120)
r.raise_for_status()
fc = r.json()
cache.write_text(json.dumps(fc))
print(f" [boundaries] {len(fc.get('features', []))} gemeente polygons")
return fc
-55
View File
@@ -1,55 +0,0 @@
"""Ingest CBS Kerncijfers wijken en buurten (gemeente grain) via OData v3.
Open data, CC-BY 4.0 (attribution: Centraal Bureau voor de Statistiek).
Table 85984NED (2024). Field keys are version-suffixed; kept in one place here.
"""
from __future__ import annotations
import json
import time
from pathlib import Path
import requests
import pandas as pd
from ..paths import CACHE_DIR
TABLE = "85984NED"
BASE = f"https://opendata.cbs.nl/ODataApi/OData/{TABLE}"
# CBS measure key -> our column name (keys confirmed from DataProperties).
FIELDS = {
"AantalInwoners_5": "inwoners",
"HuishoudensTotaal_29": "huishoudens",
"GemiddeldInkomenPerInwoner_78": "inkomen_per_inwoner",
"PersonenautoSTotaal_104": "autos_totaal",
"PersonenautoSPerHuishouden_107": "autos_per_huishouden",
"PersonenautoSOverigeBrandstof_106": "autos_overige_brandstof",
"MateVanStedelijkheid_120": "stedelijkheid",
"Omgevingsadressendichtheid_121": "adresdichtheid",
}
def fetch_cbs_gemeente(refresh: bool = False) -> pd.DataFrame:
cache = CACHE_DIR / f"cbs_{TABLE}_gemeente.json"
if cache.exists() and not refresh:
rows = json.loads(cache.read_text())
else:
select = ",".join(["WijkenEnBuurten", *FIELDS.keys()])
# Gemeente rows only (codes start with 'GM').
url = f"{BASE}/TypedDataSet?$select={select}&$filter=startswith(WijkenEnBuurten,'GM')"
rows = []
while url:
r = requests.get(url, headers={"Accept": "application/json"}, timeout=60)
r.raise_for_status()
payload = r.json()
rows.extend(payload.get("value", []))
url = payload.get("odata.nextLink") or payload.get("@odata.nextLink")
if url:
time.sleep(0.2)
cache.write_text(json.dumps(rows))
df = pd.DataFrame(rows)
df = df.rename(columns={**FIELDS, "WijkenEnBuurten": "code"})
df["code"] = df["code"].str.strip()
for col in FIELDS.values():
df[col] = pd.to_numeric(df[col], errors="coerce")
print(f" [cbs] {len(df)} gemeenten from {TABLE}")
return df.set_index("code")
-136
View File
@@ -1,136 +0,0 @@
"""Charger supply + usage per gemeente, from our own committed artifacts.
- supply: municipalities.json (counts) + crop-out GeoJSONs (power, megawatt)
- usage: latest per-gemeente snapshot day file (avg occupancy %)
"""
from __future__ import annotations
import json
import statistics
import pandas as pd
from ..paths import MUNICIPALITIES_JSON, GEMEENTEN_DIR, SNAPSHOTS_DIR
def _latest_day(slug: str) -> dict | None:
d = SNAPSHOTS_DIR / slug
if not d.is_dir():
return None
days = sorted(p for p in d.glob("*.json") if p.name != "daily.json")
return json.loads(days[-1].read_text()) if days else None
def _snapshot_metrics(slug: str) -> dict:
"""avg occupancy + live EVSE totals/charging-now from the latest snapshot.
- avg_occupancy is EVSE-weighted (a 147-connector hub weighs more than a
1-connector post), not a flat mean over location-hours.
- charging_now samples every location at the SAME hour (the latest hour with
any data), so the "now" figure is a real instant, not a blend of each
location's own last non-null hour.
"""
data = _latest_day(slug)
if not data:
return {"avg_occupancy": None, "evse_total": None, "charging_now": None, "occupancy_now": None}
locations = data.get("locations", {}).values()
evse_total = 0
w_sum = 0.0
w_total = 0.0
last_idx = -1
for loc in locations:
n = loc.get("n") or 0
evse_total += n
occ = loc.get("occ", [])
for i, v in enumerate(occ):
if v is not None:
w_sum += v * n
w_total += n
if i > last_idx:
last_idx = i
charging_now = 0
evse_now = 0
if last_idx >= 0:
for loc in locations:
n = loc.get("n") or 0
occ = loc.get("occ", [])
v = occ[last_idx] if last_idx < len(occ) else None
if v is not None:
charging_now += round(v / 100 * n)
evse_now += n
avg = round(w_sum / w_total, 1) if w_total else None
occ_now = round(100 * charging_now / evse_now, 1) if evse_now else None
return {"avg_occupancy": avg, "evse_total": evse_total, "charging_now": charging_now, "occupancy_now": occ_now}
def _crop_stats(slug: str) -> dict:
"""Per-gemeente supply stats from the crop-out, split by layer: summed power
(passenger vs freight), megawatt + dedicated-truck counts, and the €/kWh
price distribution over PASSENGER locations that publish one (freight HPC
tariffs would skew the general-public median)."""
f = GEMEENTEN_DIR / f"{slug}.geojson"
if not f.exists():
return {"power": 0.0, "freight_power": 0.0, "mw": 0, "freight_dedicated": 0,
"price_median": None, "price_mean": None, "price_n": 0}
data = json.loads(f.read_text())
power = 0.0
freight_power = 0.0
mw = 0
freight_dedicated = 0
prices: list[float] = []
for feat in data.get("features", []):
p = feat.get("properties", {})
if p.get("type") != "charge":
continue
kw = p.get("maxPowerKw") or 0
if p.get("layer") == "freight":
freight_power += kw
if p.get("isMegawatt"):
mw += 1
if p.get("freightKind") == "dedicated":
freight_dedicated += 1
else:
power += kw
price = p.get("priceKwh")
if isinstance(price, (int, float)):
prices.append(float(price))
return {
"power": power,
"freight_power": freight_power,
"mw": mw,
"freight_dedicated": freight_dedicated,
"price_median": round(statistics.median(prices), 3) if prices else None,
"price_mean": round(statistics.fmean(prices), 3) if prices else None,
"price_n": len(prices),
}
def fetch_chargers() -> pd.DataFrame:
munis = json.loads(MUNICIPALITIES_JSON.read_text())
rows = []
for m in munis:
if not m.get("code"): # skip 'nederland'
continue
slug = m["slug"]
crop = _crop_stats(slug)
snap = _snapshot_metrics(slug)
rows.append({
"code": m["code"],
"name": m["name"],
"slug": slug,
"population": m.get("population") or 0,
"chargers_passenger": m.get("passengerCount") or 0,
"chargers_freight": m.get("freightCount") or 0,
"total_power_kw": round(crop["power"] + crop["freight_power"]),
"passenger_power_kw": round(crop["power"]),
"freight_power_kw": round(crop["freight_power"]),
"freight_dedicated": crop["freight_dedicated"],
"megawatt_sites": crop["mw"],
"price_kwh_median": crop["price_median"],
"price_kwh_mean": crop["price_mean"],
"price_kwh_n": crop["price_n"],
"avg_occupancy": snap["avg_occupancy"],
"evse_total": snap["evse_total"],
"charging_now": snap["charging_now"],
"occupancy_now": snap["occupancy_now"],
})
df = pd.DataFrame(rows)
print(f" [chargers] {len(df)} gemeenten from municipalities.json + crop-outs")
return df.set_index("code")
-17
View File
@@ -1,17 +0,0 @@
"""Phase 1 analysis pipeline: golden dataset (gemeente) -> viewer layer."""
from __future__ import annotations
import sys
from .gold import build_gold
from .export import export_layer
def main() -> None:
refresh = "--refresh" in sys.argv
print("\n=== Laadpalenviewer analysis ===\n")
gold = build_gold(refresh=refresh)
export_layer(gold)
print("\n=== Analysis done ===\n")
if __name__ == "__main__":
main()
-97
View File
@@ -1,97 +0,0 @@
"""Phase 2-5 models on the gemeente-grain golden dataset.
All transparent and documented. Where real grid-capacity data is not ingested
(open Capaciteitskaart is viewer-only), congestion is a MODELLED index, flagged.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_predict, KFold
from sklearn.metrics import r2_score, mean_absolute_error
# Demand model features (socio-demographic drivers of charging demand).
FEATURES = [
"inwoners", "huishoudens", "autos_totaal", "autos_per_huishouden",
"inkomen_per_inwoner", "stedelijkheid", "adresdichtheid",
]
TARGET = "chargers_passenger"
# Load-model constants (documented, tunable).
# NDW omits max_electric_power for ~90% of connectors, so power MUST be assumed.
ASSUMED_EVSE_KW = 11.0 # blended assumed draw per EVSE (mostly AC)
AVG_FREIGHT_KW = 150.0 # typical HPC/truck connector draw
CONCURRENCY = 0.30 # planning concurrency for the potential peak
def _pct_rank(s: pd.Series) -> pd.Series:
return (s.rank(pct=True) * 100).round(0)
def add_models(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
# ---- P2: demand (peer benchmark) ----
X = df[FEATURES].apply(lambda c: c.fillna(c.median()), axis=0)
y = df[TARGET].fillna(0).astype(float)
model = RandomForestRegressor(n_estimators=300, min_samples_leaf=3, random_state=42, n_jobs=-1)
cv = KFold(n_splits=5, shuffle=True, random_state=42)
oof = cross_val_predict(model, X, y, cv=cv, n_jobs=-1)
oof = np.clip(oof, 0, None)
df["expected_chargers"] = oof.round(0)
df["supply_gap"] = (y - oof).round(0) # actual - expected; <0 = underserved
pop = df["inwoners"].fillna(df["population"]).replace(0, np.nan)
df["demand_per_1000_inw"] = (df["expected_chargers"] / pop * 1000).round(2)
# fit on all for feature importance + reported metrics
model.fit(X, y)
metrics = {
"r2_oof": round(float(r2_score(y, oof)), 3),
"mae_oof": round(float(mean_absolute_error(y, oof)), 1),
"feature_importance": dict(zip(FEATURES, model.feature_importances_.round(3).tolist())),
}
# ---- P3: optimal siting (gap-driven priority) ----
deficit = (df["expected_chargers"] - y).clip(lower=0) # how many short
rel_deficit = (deficit / df["expected_chargers"].replace(0, np.nan)).fillna(0)
occ = df["avg_occupancy"].fillna(df["avg_occupancy"].median() if df["avg_occupancy"].notna().any() else 0)
occ_norm = occ / 100.0
# priority blends absolute shortfall, relative shortfall, and usage pressure
raw = 0.5 * rel_deficit + 0.3 * (deficit / (deficit.max() or 1)) + 0.2 * occ_norm
df["siting_priority"] = (raw / (raw.max() or 1) * 100).round(0)
# ---- P4: congestion risk + net impact ----
# EVSE count: prefer live snapshot total (EVSE grain); the fallback is
# LOCATION grain (~2-10 EVSEs per location) and only fires for gemeenten
# without any snapshot — treat those rows as underestimates.
evse = df["evse_total"].fillna(df["chargers_passenger"].fillna(0) + df["chargers_freight"].fillna(0))
# Potential peak (planning): passenger EVSEs at ~11 kW plus freight/truck
# locations at ~150 kW each, x concurrency. Freight sites are counted per
# location (crop-outs don't carry per-site bay counts) — conservative for
# multi-bay hubs, but far closer than pricing an MCS hub as one AC post.
freight_locs = df["chargers_freight"].fillna(0)
passenger_evse = (evse - freight_locs).clip(lower=0)
df["potential_peak_load_kw"] = (
(passenger_evse * ASSUMED_EVSE_KW + freight_locs * AVG_FREIGHT_KW) * CONCURRENCY
).round(0)
# Live peak now (grounded in OCPI status): EVSEs charging now x assumed kW.
df["live_peak_load_kw"] = (df["charging_now"] * ASSUMED_EVSE_KW).round(0)
# Scenario base = potential peak; kept as est_peak_load_kw for the scorecard slider.
df["est_peak_load_kw"] = df["potential_peak_load_kw"]
df["load_per_1000_inw_kw"] = (df["potential_peak_load_kw"] / pop * 1000).round(1)
df["congestion_index"] = _pct_rank(df["load_per_1000_inw_kw"]) # 0-100 relative
# ---- P5: municipal percentiles (for scorecard) ----
df["supply_pct"] = _pct_rank(df["chargers_per_1000_inw"])
df["occupancy_pct"] = _pct_rank(df["avg_occupancy"]) if df["avg_occupancy"].notna().any() else np.nan
df["gap_pct"] = _pct_rank(-df["supply_gap"]) # high = more underserved
# Price percentile: high = relatively expensive vs other gemeenten.
df["price_pct"] = _pct_rank(df["price_kwh_median"]) if df["price_kwh_median"].notna().any() else np.nan
# Freight/logistics percentile: rank on installed truck-charging power.
df["freight_pct"] = _pct_rank(df["freight_power_kw"]) if df["freight_power_kw"].notna().any() else np.nan
df.attrs["model_metrics"] = metrics
print(f" [models] demand OOF R²={metrics['r2_oof']} MAE={metrics['mae_oof']}; "
f"top feature={max(metrics['feature_importance'], key=metrics['feature_importance'].get)}")
return df
-18
View File
@@ -1,18 +0,0 @@
"""Filesystem paths for the analysis layer."""
from pathlib import Path
ANALYSIS_ROOT = Path(__file__).resolve().parent.parent
PROJECT_ROOT = ANALYSIS_ROOT.parent
CACHE_DIR = ANALYSIS_ROOT / ".cache"
GOLD_DIR = ANALYSIS_ROOT / "data" # golden dataset outputs (parquet/csv)
WEBAPP_PUBLIC = PROJECT_ROOT / "webapp" / "public"
DATA_DIR = WEBAPP_PUBLIC / "data"
GEMEENTEN_DIR = DATA_DIR / "gemeenten"
SNAPSHOTS_DIR = DATA_DIR / "snapshots"
DERIVED_DIR = DATA_DIR / "derived"
MUNICIPALITIES_JSON = WEBAPP_PUBLIC / "municipalities.json"
for d in (CACHE_DIR, GOLD_DIR, DERIVED_DIR):
d.mkdir(parents=True, exist_ok=True)
-2
View File
@@ -1,2 +0,0 @@
node_modules/
.cache/
-65
View File
@@ -1,65 +0,0 @@
{
"_comment": "Hand-curated public heavy-duty / megawatt truck charging hubs in NL. Highest merge priority; never deduped away. Update as the network grows.",
"hubs": [
{
"id": "milence-venlo",
"name": "Milence Charging Hub Venlo",
"operatorName": "Milence",
"city": "Venlo",
"address": "Celsiusweg, Venlo",
"lat": 51.3942,
"lng": 6.1583,
"maxPowerKw": 400,
"isMegawatt": false,
"sourceUrl": "https://milence.com"
},
{
"id": "milence-zwolle",
"name": "Milence Charging Hub Zwolle",
"operatorName": "Milence",
"city": "Zwolle",
"address": "Hessenpoort, Zwolle",
"lat": 52.5331,
"lng": 6.1499,
"maxPowerKw": 1000,
"isMegawatt": true,
"sourceUrl": "https://milence.com"
},
{
"id": "milence-waddinxveen",
"name": "Milence Charging Hub Waddinxveen",
"operatorName": "Milence",
"city": "Waddinxveen",
"address": "Distripark Doelwijk (A12), Waddinxveen",
"lat": 52.0177,
"lng": 4.6199,
"maxPowerKw": 400,
"isMegawatt": false,
"sourceUrl": "https://milence.com/nl/press-release/milence-breidt-nederlands-netwerk-uit-in-het-hart-van-de-randstad-met-nieuwe-laadhub-in-waddinxveen/"
},
{
"id": "watthub-geldermalsen",
"name": "WattHub Geldermalsen",
"operatorName": "WattHub",
"city": "Meteren",
"address": "Rijnstraat, Meteren (Geldermalsen)",
"lat": 51.8806,
"lng": 5.2614,
"maxPowerKw": 400,
"isMegawatt": false,
"sourceUrl": "https://watthub.nl"
},
{
"id": "watthub-maasvlakte",
"name": "WattHub Maasvlakte (Port of Rotterdam)",
"operatorName": "WattHub",
"city": "Maasvlakte Rotterdam",
"address": "Maasvlakte, Rotterdam",
"lat": 51.9559,
"lng": 4.0289,
"maxPowerKw": 400,
"isMegawatt": false,
"sourceUrl": "https://watthub.nl"
}
]
}
File diff suppressed because it is too large Load Diff
-670
View File
@@ -1,670 +0,0 @@
{
"name": "laadpalenviewer-data-pipeline",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "laadpalenviewer-data-pipeline",
"version": "0.1.0",
"dependencies": {
"@turf/bbox": "^7.2.0",
"@turf/boolean-point-in-polygon": "^7.2.0",
"@turf/helpers": "^7.2.0"
},
"devDependencies": {
"@types/node": "^20",
"tsx": "^4.19.2",
"typescript": "^5"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz",
"integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz",
"integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz",
"integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz",
"integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz",
"integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz",
"integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz",
"integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz",
"integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz",
"integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz",
"integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz",
"integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz",
"integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz",
"integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz",
"integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz",
"integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz",
"integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz",
"integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz",
"integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz",
"integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz",
"integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz",
"integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz",
"integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz",
"integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz",
"integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz",
"integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz",
"integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@turf/bbox": {
"version": "7.3.5",
"resolved": "https://registry.npmjs.org/@turf/bbox/-/bbox-7.3.5.tgz",
"integrity": "sha512-oG1ya/HtBjAIg4TimbWx+nOYPbY0bCvt82Bq8tm6sBw3qqtbOyRSfDz79Sq90TnH7DXJprJ1qnVGKNtZ6jemfw==",
"license": "MIT",
"dependencies": {
"@turf/helpers": "7.3.5",
"@turf/meta": "7.3.5",
"@types/geojson": "^7946.0.10",
"tslib": "^2.8.1"
},
"funding": {
"url": "https://opencollective.com/turf"
}
},
"node_modules/@turf/boolean-point-in-polygon": {
"version": "7.3.5",
"resolved": "https://registry.npmjs.org/@turf/boolean-point-in-polygon/-/boolean-point-in-polygon-7.3.5.tgz",
"integrity": "sha512-ba7+B0wzaS9GtERZOoXUZ6oW8IcIJHNQZf3c+tiD9ESjcsPO1Q/4qIJGTKl92nBLhhracHJxMWBM/U6hAVkaRg==",
"license": "MIT",
"dependencies": {
"@turf/helpers": "7.3.5",
"@turf/invariant": "7.3.5",
"@types/geojson": "^7946.0.10",
"point-in-polygon-hao": "^1.1.0",
"tslib": "^2.8.1"
},
"funding": {
"url": "https://opencollective.com/turf"
}
},
"node_modules/@turf/helpers": {
"version": "7.3.5",
"resolved": "https://registry.npmjs.org/@turf/helpers/-/helpers-7.3.5.tgz",
"integrity": "sha512-E/NMGV5MwbjjP7AJXBtsanC3yY8N2MQ87IGdIgkB2ji5AtBpwnH4L3gEqpYN4RlCJJWbLbzO91BbKv2waUd0eg==",
"license": "MIT",
"dependencies": {
"@types/geojson": "^7946.0.10",
"tslib": "^2.8.1"
},
"funding": {
"url": "https://opencollective.com/turf"
}
},
"node_modules/@turf/invariant": {
"version": "7.3.5",
"resolved": "https://registry.npmjs.org/@turf/invariant/-/invariant-7.3.5.tgz",
"integrity": "sha512-ZVIvsBvjr8lO7WxC5zYNjRsjSDvyGvWkJMjuWaJjTU8x+1tmfNnw3gDX/TI2Sit83gcRYLYkNo23lB/udqx/Hg==",
"license": "MIT",
"dependencies": {
"@turf/helpers": "7.3.5",
"@types/geojson": "^7946.0.10",
"tslib": "^2.8.1"
},
"funding": {
"url": "https://opencollective.com/turf"
}
},
"node_modules/@turf/meta": {
"version": "7.3.5",
"resolved": "https://registry.npmjs.org/@turf/meta/-/meta-7.3.5.tgz",
"integrity": "sha512-r+ohqxoyqeigFB0oFrQx/YEHIkOKqcKpCjvZkvZs7Tkv+IFco5MezAd2zd4rzK+0DfFgDP3KpJc7HqrYjvEjhg==",
"license": "MIT",
"dependencies": {
"@turf/helpers": "7.3.5",
"@types/geojson": "^7946.0.10",
"tslib": "^2.8.1"
},
"funding": {
"url": "https://opencollective.com/turf"
}
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "20.19.41",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz",
"integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/esbuild": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz",
"integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.0",
"@esbuild/android-arm": "0.28.0",
"@esbuild/android-arm64": "0.28.0",
"@esbuild/android-x64": "0.28.0",
"@esbuild/darwin-arm64": "0.28.0",
"@esbuild/darwin-x64": "0.28.0",
"@esbuild/freebsd-arm64": "0.28.0",
"@esbuild/freebsd-x64": "0.28.0",
"@esbuild/linux-arm": "0.28.0",
"@esbuild/linux-arm64": "0.28.0",
"@esbuild/linux-ia32": "0.28.0",
"@esbuild/linux-loong64": "0.28.0",
"@esbuild/linux-mips64el": "0.28.0",
"@esbuild/linux-ppc64": "0.28.0",
"@esbuild/linux-riscv64": "0.28.0",
"@esbuild/linux-s390x": "0.28.0",
"@esbuild/linux-x64": "0.28.0",
"@esbuild/netbsd-arm64": "0.28.0",
"@esbuild/netbsd-x64": "0.28.0",
"@esbuild/openbsd-arm64": "0.28.0",
"@esbuild/openbsd-x64": "0.28.0",
"@esbuild/openharmony-arm64": "0.28.0",
"@esbuild/sunos-x64": "0.28.0",
"@esbuild/win32-arm64": "0.28.0",
"@esbuild/win32-ia32": "0.28.0",
"@esbuild/win32-x64": "0.28.0"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/point-in-polygon-hao": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/point-in-polygon-hao/-/point-in-polygon-hao-1.2.4.tgz",
"integrity": "sha512-x2pcvXeqhRHlNRdhLs/tgFapAbSSe86wa/eqmj1G6pWftbEs5aVRJhRGM6FYSUERKu0PjekJzMq0gsI2XyiclQ==",
"license": "MIT",
"dependencies": {
"robust-predicates": "^3.0.2"
}
},
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsx": {
"version": "4.22.4",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz",
"integrity": "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
}
}
}
-22
View File
@@ -1,22 +0,0 @@
{
"name": "laadpalenviewer-data-pipeline",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Generation pipeline: NDW OCPI + external freight + PDOK CBS boundaries -> static GeoJSON/JSON for the webapp",
"scripts": {
"generate": "tsx src/index.ts",
"generate:nocache": "tsx src/index.ts --refresh",
"snapshot": "tsx src/snapshot.ts"
},
"dependencies": {
"@turf/bbox": "^7.2.0",
"@turf/boolean-point-in-polygon": "^7.2.0",
"@turf/helpers": "^7.2.0"
},
"devDependencies": {
"@types/node": "^20",
"tsx": "^4.19.2",
"typescript": "^5"
}
}
-65
View File
@@ -1,65 +0,0 @@
// Assign each point to a gemeente via bbox pre-filter + point-in-polygon.
import booleanPointInPolygon from '@turf/boolean-point-in-polygon';
import { point } from '@turf/helpers';
import type { Boundaries, BoundaryFeature } from './fetchBoundaries.js';
export interface Assignable {
lat: number;
lng: number;
}
export class GemeenteAssigner {
private gemeenten: BoundaryFeature[];
private bboxes: Map<string, [number, number, number, number]>;
constructor(boundaries: Boundaries) {
this.gemeenten = boundaries.gemeenten;
this.bboxes = boundaries.gemeenteBboxes;
}
// Returns the gemeente statcode (e.g. "GM0344") or null if no polygon matches.
assign(item: Assignable): string | null {
const { lat, lng } = item;
const pt = point([lng, lat]);
for (const g of this.gemeenten) {
const b = this.bboxes.get(g.properties.statcode);
if (!b) continue;
if (lng < b[0] || lng > b[2] || lat < b[1] || lat > b[3]) continue; // bbox reject
if (booleanPointInPolygon(pt, g as any)) {
return g.properties.statcode;
}
}
return null;
}
// Like assign(), but falls back to the nearest gemeente (by bbox distance) for
// points that miss every generalized polygon — reclaimed/industrial land such as
// the Maasvlakte sits outside the simplified coastline. Returns null beyond ~15 km.
assignWithFallback(item: Assignable): { code: string; fallback: boolean } | null {
const exact = this.assign(item);
if (exact) return { code: exact, fallback: false };
const { lat, lng } = item;
const cosLat = Math.cos((lat * Math.PI) / 180);
let best: string | null = null;
let bestD = Infinity;
for (const g of this.gemeenten) {
const b = this.bboxes.get(g.properties.statcode);
if (!b) continue;
const dx = (lng < b[0] ? b[0] - lng : lng > b[2] ? lng - b[2] : 0) * cosLat;
const dy = lat < b[1] ? b[1] - lat : lat > b[3] ? lat - b[3] : 0;
let d = Math.hypot(dx, dy);
if (d === 0) {
// Inside the bbox but outside the polygon: rank by distance to bbox centre,
// scaled down so any bbox hit beats a near-miss on a neighbouring bbox.
const cx = ((b[0] + b[2]) / 2 - lng) * cosLat;
const cy = (b[1] + b[3]) / 2 - lat;
d = Math.hypot(cx, cy) * 0.01;
}
if (d < bestD) {
bestD = d;
best = g.properties.statcode;
}
}
return best && bestD <= 0.15 ? { code: best, fallback: true } : null;
}
}
-154
View File
@@ -1,154 +0,0 @@
// Classify an OCPI location as passenger vs freight (heavy-duty / truck) charging.
// Signals, in decreasing precision: dedicated truck operator, explicit truck naming,
// logistics-depot naming + serious DC power, MCS standard, parking_type, raw DC power.
// Locations that only qualify on raw DC power are marked freightKind 'hpc'
// (truck-capable high-power charging, e.g. 400 kW Fastned/IONITY lanes that a tractor-
// trailer may not physically fit); everything else is 'dedicated'.
import type { OCPILocation, OCPIConnector, ClassificationMeta, AggregateStatus } from './types.js';
// Aggregate EVSE statuses into one availability value (fleetsim priority:
// AVAILABLE > CHARGING > any other status -> UNAVAILABLE; no EVSEs -> UNKNOWN).
export function aggregateStatus(loc: OCPILocation): AggregateStatus {
const evses = loc.evses ?? [];
if (evses.length === 0) return 'UNKNOWN';
if (evses.some((e) => e.status === 'AVAILABLE')) return 'AVAILABLE';
if (evses.some((e) => e.status === 'CHARGING')) return 'CHARGING';
return 'UNAVAILABLE';
}
export const THRESHOLDS = {
// Watts. A DC connector at/above this makes a location truck-capable ('hpc').
// 350 kW+ is above the CCS power most passenger cars can take, but several
// passenger networks (Fastned/IONITY) run 400 kW lanes, so power alone is only
// a 'truck-capable' signal, never a 'dedicated truck facility' signal.
FREIGHT_DC_WATTS: 350_000,
// Watts. Megawatt Charging System territory.
MEGAWATT_WATTS: 1_000_000,
// Watts. Minimum DC power for a logistics-named depot / motorway parking to count.
DEPOT_MIN_DC_WATTS: 150_000,
PARKING_MIN_DC_WATTS: 350_000,
// Plausibility caps for declared connector power. NDW carries garbage like
// 7,360,000 W on a 230 V / 32 A AC post; above the cap we fall back to V×A.
MAX_PLAUSIBLE_WATTS: 1_500_000,
MAX_PLAUSIBLE_MCS_WATTS: 4_000_000,
} as const;
// Operators whose sites are dedicated heavy-duty / truck hubs.
const FREIGHT_OPERATOR_PATTERNS = [
'milence',
'watthub',
'wattev',
'einride',
'heliox truck',
];
// Explicit truck naming on the location itself ("Truck only", "Truckpoint",
// "E-Truck", "vrachtwagen", ...). High precision in the NDW feed, but "heftruck"/
// "vorkheftruck" (forklift) and "pallettruck" must not match.
const TRUCK_NAME_RE = /truck|vracht|zwaar vervoer/i;
const FORKLIFT_RE = /(hef|vorkhef|pallet|steek)truck/gi;
function nameMentionsTruck(name: string): boolean {
return TRUCK_NAME_RE.test(name.replace(FORKLIFT_RE, ''));
}
// Logistics-depot naming; only counts as freight when paired with serious DC power,
// so a 22 kW AC post at a transport company's visitor parking stays passenger.
const DEPOT_NAME_RE = /logisti|distributiecentr|transport/i;
// parking_type values that hint at freight/truck use.
const FREIGHT_PARKING_TYPES = new Set([
'ALONG_MOTORWAY',
]);
const CCS_STANDARDS = new Set([
'IEC_62196_T2_COMBO',
]);
function isMcsStandard(standard: string): boolean {
const s = (standard || '').toUpperCase();
return s.startsWith('MCS') || s.includes('MEGAWATT') || s === 'IEC_63379';
}
function normalize(s: string | undefined): string {
return (s ?? '').toLowerCase().trim();
}
// Best-effort connector power in watts. Prefers the declared max_electric_power
// when plausible; otherwise derives from V×A (×3 for three-phase AC), which
// recovers power for the ~50% of NDW connectors that omit max_electric_power
// and neutralizes implausible declared values.
export function connectorPowerW(c: OCPIConnector): number {
const declared = c.max_electric_power ?? 0;
const cap = isMcsStandard(c.standard)
? THRESHOLDS.MAX_PLAUSIBLE_MCS_WATTS
: THRESHOLDS.MAX_PLAUSIBLE_WATTS;
if (declared > 0 && declared <= cap) return declared;
const v = c.max_voltage ?? 0;
const a = c.max_amperage ?? 0;
if (v <= 0 || a <= 0) return 0;
const phases = (c.power_type ?? '').toUpperCase() === 'AC_3_PHASE' ? 3 : 1;
return v * a * phases;
}
export function classifyLocation(loc: OCPILocation): ClassificationMeta {
let maxPowerW = 0;
let maxDcPowerW = 0;
let hasCCS = false;
let hasMCS = false;
let dcCount = 0;
for (const evse of loc.evses ?? []) {
for (const c of evse.connectors ?? []) {
const power = connectorPowerW(c);
if (power > maxPowerW) maxPowerW = power;
const isDc = (c.power_type ?? '').toUpperCase() === 'DC';
if (isDc) {
dcCount++;
if (power > maxDcPowerW) maxDcPowerW = power;
}
if (CCS_STANDARDS.has(c.standard)) hasCCS = true;
if (isMcsStandard(c.standard)) hasMCS = true;
}
}
const maxPowerKw = Math.round(maxPowerW / 1000);
const isMegawatt = maxPowerW >= THRESHOLDS.MEGAWATT_WATTS || hasMCS;
const operator = normalize(loc.operator?.name);
const operatorIsFreight = FREIGHT_OPERATOR_PATTERNS.some((p) => operator.includes(p));
const name = loc.name ?? '';
const nameIsTruck = nameMentionsTruck(name);
const nameIsDepot = DEPOT_NAME_RE.test(name) && maxDcPowerW >= THRESHOLDS.DEPOT_MIN_DC_WATTS;
const parkingIsFreight =
!!loc.parking_type &&
FREIGHT_PARKING_TYPES.has(loc.parking_type) &&
maxDcPowerW >= THRESHOLDS.PARKING_MIN_DC_WATTS;
// Dedicated truck facility: an explicit signal beyond raw power.
let freightReason: ClassificationMeta['freightReason'];
if (operatorIsFreight) freightReason = 'operator';
else if (nameIsTruck) freightReason = 'truck-name';
else if (hasMCS) freightReason = 'mcs';
else if (nameIsDepot) freightReason = 'depot-name';
else if (parkingIsFreight) freightReason = 'motorway';
const isDedicated = freightReason !== undefined;
const isTruckCapableHpc = !isDedicated && maxDcPowerW >= THRESHOLDS.FREIGHT_DC_WATTS;
if (isTruckCapableHpc) freightReason = 'power';
const isFreight = isDedicated || isTruckCapableHpc;
return {
category: isFreight ? 'freight' : 'passenger',
maxPowerKw,
hasCCS,
hasMCS,
isMegawatt,
dcCount,
...(isFreight ? { freightKind: isDedicated ? 'dedicated' : 'hpc', freightReason } : {}),
};
}
-82
View File
@@ -1,82 +0,0 @@
// Fetch gemeente + provincie boundaries from the PDOK CBS Gebiedsindelingen WFS.
// Generalized layers, GeoJSON output, EPSG:4326 ([lon,lat]).
import { readFile, writeFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
import bbox from '@turf/bbox';
import { CACHE_DIR } from './paths.js';
export const BOUNDARY_YEAR = process.env.BOUNDARY_YEAR ?? '2025';
const WFS_BASE = `https://service.pdok.nl/cbs/gebiedsindelingen/${BOUNDARY_YEAR}/wfs/v1_0`;
const PAGE_SIZE = 1000;
const MAX_CACHE_AGE_MS = 7 * 24 * 60 * 60 * 1000;
export interface BoundaryFeature {
type: 'Feature';
properties: { statcode: string; statnaam: string; rubriek?: string };
geometry: { type: 'Polygon' | 'MultiPolygon'; coordinates: unknown };
}
export interface BoundaryCollection {
type: 'FeatureCollection';
features: BoundaryFeature[];
}
async function fetchAllPages(typeName: string): Promise<BoundaryFeature[]> {
const features: BoundaryFeature[] = [];
let startIndex = 0;
// Defensive paging: stop when a page returns fewer than PAGE_SIZE.
for (;;) {
const url =
`${WFS_BASE}?service=WFS&version=2.0.0&request=GetFeature` +
`&typeName=${encodeURIComponent(typeName)}` +
`&outputFormat=application/json&srsName=EPSG:4326` +
`&count=${PAGE_SIZE}&startIndex=${startIndex}`;
const res = await fetch(url, { headers: { Accept: 'application/json' } });
if (!res.ok) throw new Error(`PDOK WFS ${res.status} for ${typeName}`);
const data = (await res.json()) as BoundaryCollection;
const page = data.features ?? [];
features.push(...page);
if (page.length < PAGE_SIZE) break;
startIndex += PAGE_SIZE;
}
return features;
}
async function cachedFetch(typeName: string, cacheName: string, refresh: boolean): Promise<BoundaryFeature[]> {
const cachePath = join(CACHE_DIR, cacheName);
if (!refresh) {
try {
const s = await stat(cachePath);
if (Date.now() - s.mtimeMs < MAX_CACHE_AGE_MS) {
return JSON.parse(await readFile(cachePath, 'utf-8')) as BoundaryFeature[];
}
} catch {
/* fall through to fetch */
}
}
const features = await fetchAllPages(typeName);
await writeFile(cachePath, JSON.stringify(features));
return features;
}
export interface Boundaries {
gemeenten: BoundaryFeature[];
provinces: BoundaryFeature[];
// Precomputed bbox per gemeente: [minX, minY, maxX, maxY]
gemeenteBboxes: Map<string, [number, number, number, number]>;
}
export async function fetchBoundaries(refresh = false): Promise<Boundaries> {
console.log(`Fetching PDOK CBS boundaries (year ${BOUNDARY_YEAR})...`);
const [gemeenten, provinces] = await Promise.all([
cachedFetch('gebiedsindelingen:gemeente_gegeneraliseerd', `gemeenten-${BOUNDARY_YEAR}.json`, refresh),
cachedFetch('gebiedsindelingen:provincie_gegeneraliseerd', `provincies-${BOUNDARY_YEAR}.json`, refresh),
]);
const gemeenteBboxes = new Map<string, [number, number, number, number]>();
for (const g of gemeenten) {
gemeenteBboxes.set(g.properties.statcode, bbox(g as any) as [number, number, number, number]);
}
console.log(` ${gemeenten.length} gemeenten, ${provinces.length} provinces`);
return { gemeenten, provinces, gemeenteBboxes };
}
-93
View File
@@ -1,93 +0,0 @@
// Download + gunzip + parse the NDW OCPI open-data feeds.
// Adapted from fleetsim/scripts/import-charging-points.ts (Prisma upsert removed).
import { gunzipSync } from 'node:zlib';
import { createWriteStream } from 'node:fs';
import { mkdir, readFile, stat } from 'node:fs/promises';
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';
import { join } from 'node:path';
import { CACHE_DIR } from './paths.js';
import type { OCPILocation, OCPITariff } from './types.js';
const NDW_LOCATIONS_URL = 'https://opendata.ndw.nu/charging_point_locations_ocpi.json.gz';
const NDW_TARIFFS_URL = 'https://opendata.ndw.nu/charging_point_tariffs_ocpi.json.gz';
// Re-download cached files older than this (ms). Default: 12 hours.
const MAX_CACHE_AGE_MS = 12 * 60 * 60 * 1000;
async function fileFreshEnough(path: string): Promise<boolean> {
try {
const s = await stat(path);
return Date.now() - s.mtimeMs < MAX_CACHE_AGE_MS;
} catch {
return false;
}
}
async function download(url: string, outputPath: string): Promise<void> {
await mkdir(CACHE_DIR, { recursive: true });
const response = await fetch(url);
if (!response.ok || !response.body) {
throw new Error(`Failed to download ${url}: ${response.status} ${response.statusText}`);
}
const fileStream = createWriteStream(outputPath);
await pipeline(Readable.fromWeb(response.body as any), fileStream);
}
async function loadGzJson<T>(url: string, cacheName: string, refresh: boolean): Promise<T> {
const cachePath = join(CACHE_DIR, cacheName);
const fresh = !refresh && (await fileFreshEnough(cachePath));
if (fresh) {
console.log(` using cached ${cacheName}`);
} else {
console.log(` downloading ${cacheName} ...`);
try {
await download(url, cachePath);
} catch (err) {
// Fall back to a stale cache if the download fails.
if (await fileFreshEnough(cachePath).catch(() => false) || (await stat(cachePath).then(() => true).catch(() => false))) {
console.warn(` download failed, falling back to cached ${cacheName}: ${(err as Error).message}`);
} else {
throw err;
}
}
}
const buffer = await readFile(cachePath);
const json = gunzipSync(buffer).toString('utf-8');
return JSON.parse(json) as T;
}
function isUsable(loc: OCPILocation): boolean {
if (loc.publish === false) return false;
const lat = Number.parseFloat(loc.coordinates?.latitude ?? '');
const lng = Number.parseFloat(loc.coordinates?.longitude ?? '');
return Number.isFinite(lat) && Number.isFinite(lng);
}
// Locations only — used by the hourly snapshot job (no tariffs needed).
export async function fetchNdwLocations(refresh = false): Promise<OCPILocation[]> {
const raw = await loadGzJson<OCPILocation[]>(NDW_LOCATIONS_URL, 'charging-locations.json.gz', refresh);
return raw.filter(isUsable);
}
export interface NdwData {
locations: OCPILocation[];
tariffMap: Map<string, OCPITariff>;
}
export async function fetchNdw(refresh = false): Promise<NdwData> {
console.log('Fetching NDW OCPI data...');
const [rawLocations, tariffs] = await Promise.all([
loadGzJson<OCPILocation[]>(NDW_LOCATIONS_URL, 'charging-locations.json.gz', refresh),
loadGzJson<OCPITariff[]>(NDW_TARIFFS_URL, 'charging-tariffs.json.gz', refresh),
]);
const locations = rawLocations.filter(isUsable);
const tariffMap = new Map<string, OCPITariff>();
for (const t of tariffs) tariffMap.set(t.id, t);
console.log(` loaded ${locations.length} published locations, ${tariffMap.size} tariffs`);
return { locations, tariffMap };
}
-192
View File
@@ -1,192 +0,0 @@
// Orchestrator: NDW OCPI + external freight + PDOK boundaries -> static files.
import { fetchNdw } from './fetchNdw.js';
import { classifyLocation, aggregateStatus, connectorPowerW } from './classifyFreight.js';
import { fetchBoundaries } from './fetchBoundaries.js';
import { writeOutputs } from './writeOutputs.js';
import { sanitizeId } from './slugify.js';
import { curatedSource } from './sources/curated.js';
import { eafoSource } from './sources/eafo.js';
import { openChargeMapSource } from './sources/openChargeMap.js';
import { mergeFreight } from './sources/merge.js';
import { resolveConnectorPrice } from './tariff.js';
import type { FreightSource } from './sources/types.js';
import type {
OCPILocation,
OCPITariff,
LightLocation,
EnrichedLocation,
NormalizedFreightLocation,
ClassificationMeta,
} from './types.js';
const EXTERNAL_SOURCES: FreightSource[] = [curatedSource, eafoSource, openChargeMapSource];
function enrich(
loc: OCPILocation,
meta: ClassificationMeta,
tariffMap: Map<string, OCPITariff>,
locationId: string,
now: Date,
): EnrichedLocation {
return {
locationId,
ocpiId: loc.id,
name: loc.name || loc.address,
address: loc.address,
city: loc.city,
postalCode: loc.postal_code,
country: loc.country,
latitude: Number.parseFloat(loc.coordinates.latitude),
longitude: Number.parseFloat(loc.coordinates.longitude),
parkingType: loc.parking_type,
operatorName: loc.operator?.name ?? 'Onbekend',
operatorWebsite: loc.operator?.website,
ownerName: loc.owner?.name,
twentyFourSeven: loc.opening_times?.twentyfourseven ?? false,
lastUpdated: loc.last_updated,
layer: meta.category,
maxPowerKw: meta.maxPowerKw,
freightKind: meta.freightKind,
freightReason: meta.freightReason,
evses: (loc.evses ?? []).map((evse) => ({
...evse,
connectors: (evse.connectors ?? []).map((c) => {
const tariffs = (c.tariff_ids ?? [])
.map((id) => tariffMap.get(id))
.filter((t): t is OCPITariff => Boolean(t));
const powerKw = connectorPowerW(c) / 1000;
const resolved = resolveConnectorPrice(tariffs, powerKw, now);
return {
...c,
tariffs,
...(resolved ? { priceKwh: resolved.price, priceVat: resolved.vat } : {}),
};
}),
})),
};
}
// Cheapest resolved €/kWh across a location's connectors (the headline shown on
// the map / used by the analysis layer). undefined when no connector has a price.
function locationPriceKwh(loc: EnrichedLocation): number | undefined {
let min: number | undefined;
for (const e of loc.evses) {
for (const c of e.connectors) {
if (typeof c.priceKwh === 'number' && (min === undefined || c.priceKwh < min)) min = c.priceKwh;
}
}
return min;
}
async function main() {
const refresh = process.argv.includes('--refresh');
const now = new Date();
const generatedAt = now.toISOString();
console.log(`\n=== Laadpalenviewer data pipeline (${generatedAt}) ===\n`);
// 1. NDW OCPI.
const { locations, tariffMap } = await fetchNdw(refresh);
// 2. Classify + build lights + enriched.
const passengerLights: LightLocation[] = [];
const ndwFreightNormalized: NormalizedFreightLocation[] = [];
const enrichedById = new Map<string, EnrichedLocation>();
let freightFromNdw = 0;
for (const loc of locations) {
const meta = classifyLocation(loc);
const status = aggregateStatus(loc);
const lat = Number.parseFloat(loc.coordinates.latitude);
const lng = Number.parseFloat(loc.coordinates.longitude);
const locationId = sanitizeId(loc.id);
const enriched = enrich(loc, meta, tariffMap, locationId, now);
enrichedById.set(locationId, enriched);
const priceKwh = locationPriceKwh(enriched);
if (meta.category === 'passenger') {
passengerLights.push({
locationId,
ocpiId: loc.id,
name: loc.name || loc.address,
address: loc.address,
city: loc.city,
operatorName: loc.operator?.name,
lat,
lng,
layer: 'passenger',
maxPowerKw: meta.maxPowerKw,
isMegawatt: meta.isMegawatt,
status,
source: 'ndw',
priceKwh,
});
} else {
freightFromNdw++;
ndwFreightNormalized.push({
id: locationId, // matches enrichedById key so detail bundle resolves
source: 'ndw',
name: loc.name || loc.address,
address: loc.address,
city: loc.city,
lat,
lng,
operatorName: loc.operator?.name,
maxPowerKw: meta.maxPowerKw,
isMegawatt: meta.isMegawatt,
status,
priceKwh,
freightKind: meta.freightKind,
freightReason: meta.freightReason,
});
}
}
console.log(` classified: ${passengerLights.length} passenger, ${freightFromNdw} freight (NDW)`);
// 3. External freight sources (each isolated; failure -> skip).
const externalGroups: NormalizedFreightLocation[][] = [];
for (const src of EXTERNAL_SOURCES) {
try {
const items = await src.fetch(refresh);
console.log(` [${src.id}] ${items.length} freight locations`);
externalGroups.push(items);
} catch (err) {
console.warn(` [${src.id}] failed, skipping: ${(err as Error).message}`);
}
}
// 4. Merge + dedupe freight.
const mergedFreight = mergeFreight([ndwFreightNormalized, ...externalGroups]);
console.log(` merged freight (deduped): ${mergedFreight.length}`);
const freightLights: LightLocation[] = mergedFreight.map((f) => ({
locationId: f.id,
name: f.name,
address: f.address,
city: f.city,
operatorName: f.operatorName,
lat: f.lat,
lng: f.lng,
layer: 'freight',
maxPowerKw: f.maxPowerKw,
isMegawatt: f.isMegawatt ?? false,
status: f.status ?? 'UNKNOWN',
source: f.source,
sourceUrl: f.sourceUrl,
priceKwh: f.priceKwh,
freightKind: f.freightKind ?? 'dedicated',
freightReason: f.freightReason ?? 'curated',
}));
// 5. Boundaries.
const boundaries = await fetchBoundaries(refresh);
// 6. Write.
await writeOutputs({ passengerLights, freightLights, enrichedById, boundaries, generatedAt });
console.log('\n=== Done ===\n');
}
main().catch((err) => {
console.error('Pipeline failed:', err);
process.exit(1);
});
-21
View File
@@ -1,21 +0,0 @@
// Centralized filesystem paths for the pipeline.
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
const __dirname = dirname(fileURLToPath(import.meta.url));
// data-pipeline/
export const PIPELINE_ROOT = resolve(__dirname, '..');
// laadpalenviewer/
export const PROJECT_ROOT = resolve(PIPELINE_ROOT, '..');
export const CACHE_DIR = join(PIPELINE_ROOT, '.cache');
export const PIPELINE_DATA_DIR = join(PIPELINE_ROOT, 'data');
// webapp output targets
export const WEBAPP_PUBLIC = join(PROJECT_ROOT, 'webapp', 'public');
export const DATA_DIR = join(WEBAPP_PUBLIC, 'data');
export const GEMEENTEN_DIR = join(DATA_DIR, 'gemeenten');
export const SNAPSHOTS_DIR = join(DATA_DIR, 'snapshots');
export const STATUS_DIR = join(DATA_DIR, 'status');
export const MUNICIPALITIES_JSON = join(WEBAPP_PUBLIC, 'municipalities.json');
-17
View File
@@ -1,17 +0,0 @@
// Deterministic slug for gemeente names and a URL-safe id sanitizer.
export function slugify(name: string): string {
return name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '') // strip diacritics
.toLowerCase()
.replace(/['’.]/g, '') // drop apostrophes (straight + curly) and periods
.replace(/[^a-z0-9]+/g, '-') // non-alphanumerics -> hyphen
.replace(/^-+|-+$/g, '') // trim hyphens
.replace(/-+/g, '-');
}
// OCPI ids can contain '*', '/', spaces, etc. Make a stable, filesystem/URL-safe id.
export function sanitizeId(id: string): string {
return id.replace(/[^A-Za-z0-9_-]+/g, '_');
}
-203
View File
@@ -1,203 +0,0 @@
// Hourly snapshot job: download NDW OCPI gz, compute per-location occupancy% +
// aggregate status, group by gemeente, append an hourly sample to per-gemeente
// per-day files, refresh per-gemeente current-status files, then roll up old
// hourly files into daily averages and prune.
//
// Run by the GitHub Action (and locally via `npm run snapshot`).
import { readdir, readFile, writeFile, mkdir, rm, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { fetchNdwLocations } from './fetchNdw.js';
import { aggregateStatus } from './classifyFreight.js';
import { sanitizeId } from './slugify.js';
import { GEMEENTEN_DIR, SNAPSHOTS_DIR, STATUS_DIR } from './paths.js';
import type { OCPILocation, AggregateStatus } from './types.js';
const HOURLY_RETENTION_DAYS = 30; // keep raw hourly files this long
const DAILY_RETENTION_DAYS = 365; // keep daily averages this long
interface DayFile {
date: string;
tz: string;
locations: Record<string, { n: number; occ: (number | null)[] }>;
}
type DailyFile = Record<string, Record<string, number>>; // locId -> { date -> avgOcc }
// Amsterdam-local date (YYYY-MM-DD) + hour (0-23) for "over the day" semantics.
function amsterdamNow(): { date: string; hour: number } {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Amsterdam',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
hour12: false,
}).formatToParts(new Date());
const get = (t: string) => parts.find((p) => p.type === t)?.value ?? '';
const date = `${get('year')}-${get('month')}-${get('day')}`;
const hour = Number.parseInt(get('hour'), 10) % 24;
return { date, hour };
}
function dayNumber(date: string): number {
return Math.floor(Date.parse(`${date}T00:00:00Z`) / 86_400_000);
}
// Build locationId -> gemeente slug from the committed crop-out GeoJSONs.
async function buildSlugMap(): Promise<Map<string, string>> {
const map = new Map<string, string>();
let files: string[] = [];
try {
files = (await readdir(GEMEENTEN_DIR)).filter((f) => f.endsWith('.geojson'));
} catch {
throw new Error(`No crop-outs found in ${GEMEENTEN_DIR}; run the full pipeline first.`);
}
for (const f of files) {
const slug = f.replace(/\.geojson$/, '');
const data = JSON.parse(await readFile(join(GEMEENTEN_DIR, f), 'utf-8')) as {
features: Array<{ properties: { type: string; locationId?: string } }>;
};
for (const feat of data.features) {
if (feat.properties.type === 'charge' && feat.properties.locationId) {
map.set(feat.properties.locationId, slug);
}
}
}
return map;
}
function occupancyAndStatus(loc: OCPILocation): { n: number; occ: number | null; status: AggregateStatus } {
const evses = loc.evses ?? [];
const n = evses.length;
const status = aggregateStatus(loc);
if (n === 0) return { n: 0, occ: null, status };
const charging = evses.filter((e) => e.status === 'CHARGING').length;
// "Usage" = share of connectors actively charging.
return { n, occ: Math.round((100 * charging) / n), status };
}
async function readJson<T>(path: string): Promise<T | null> {
try {
return JSON.parse(await readFile(path, 'utf-8')) as T;
} catch {
return null;
}
}
async function main() {
const refresh = true; // always pull a fresh gz in the hourly job
const { date, hour } = amsterdamNow();
console.log(`\n=== Charging snapshot ${date} hour ${hour} (Europe/Amsterdam) ===`);
const [locations, slugMap] = await Promise.all([fetchNdwLocations(refresh), buildSlugMap()]);
console.log(` ${locations.length} locations, ${slugMap.size} mapped to a gemeente`);
// Group this hour's samples + statuses by gemeente.
const byGemeente = new Map<string, Map<string, { n: number; occ: number | null }>>();
const statusByGemeente = new Map<string, Record<string, AggregateStatus>>();
let sampled = 0;
for (const loc of locations) {
const locId = sanitizeId(loc.id);
const slug = slugMap.get(locId);
if (!slug) continue;
const { n, occ, status } = occupancyAndStatus(loc);
let g = byGemeente.get(slug);
if (!g) byGemeente.set(slug, (g = new Map()));
g.set(locId, { n, occ });
let s = statusByGemeente.get(slug);
if (!s) statusByGemeente.set(slug, (s = {}));
s[locId] = status;
sampled++;
}
console.log(` sampled ${sampled} locations across ${byGemeente.size} gemeenten`);
await mkdir(STATUS_DIR, { recursive: true });
// Append hourly samples + write current-status per gemeente.
for (const [slug, samples] of byGemeente) {
const dir = join(SNAPSHOTS_DIR, slug);
await mkdir(dir, { recursive: true });
const dayPath = join(dir, `${date}.json`);
const day = (await readJson<DayFile>(dayPath)) ?? { date, tz: 'Europe/Amsterdam', locations: {} };
for (const [locId, { n, occ }] of samples) {
let entry = day.locations[locId];
if (!entry) entry = day.locations[locId] = { n, occ: Array(24).fill(null) };
entry.n = n;
entry.occ[hour] = occ;
}
await writeFile(dayPath, JSON.stringify(day));
await writeFile(join(STATUS_DIR, `${slug}.json`), JSON.stringify(statusByGemeente.get(slug) ?? {}));
}
await rollupAndPrune(date);
console.log('=== Snapshot done ===\n');
}
// Collapse hourly files older than HOURLY_RETENTION_DAYS into per-gemeente daily
// averages, delete them, and trim daily entries older than DAILY_RETENTION_DAYS.
async function rollupAndPrune(today: string): Promise<void> {
const todayNum = dayNumber(today);
let slugs: string[] = [];
try {
slugs = await readdir(SNAPSHOTS_DIR);
} catch {
return;
}
let rolled = 0;
let pruned = 0;
for (const slug of slugs) {
const dir = join(SNAPSHOTS_DIR, slug);
let entries: string[];
try {
if (!(await stat(dir)).isDirectory()) continue;
entries = await readdir(dir);
} catch {
continue;
}
const dailyPath = join(dir, 'daily.json');
const daily = (await readJson<DailyFile>(dailyPath)) ?? {};
let dailyChanged = false;
for (const file of entries) {
const m = file.match(/^(\d{4}-\d{2}-\d{2})\.json$/);
if (!m) continue;
const fileDate = m[1];
const age = todayNum - dayNumber(fileDate);
if (age <= HOURLY_RETENTION_DAYS) continue;
const day = await readJson<DayFile>(join(dir, file));
if (day) {
for (const [locId, { occ }] of Object.entries(day.locations)) {
const vals = occ.filter((v): v is number => v !== null);
if (vals.length === 0) continue;
const avg = Math.round(vals.reduce((a, b) => a + b, 0) / vals.length);
(daily[locId] ??= {})[fileDate] = avg;
}
}
await rm(join(dir, file), { force: true });
rolled++;
dailyChanged = true;
}
// Trim daily entries older than DAILY_RETENTION_DAYS.
for (const locId of Object.keys(daily)) {
for (const d of Object.keys(daily[locId])) {
if (todayNum - dayNumber(d) > DAILY_RETENTION_DAYS) {
delete daily[locId][d];
dailyChanged = true;
pruned++;
}
}
if (Object.keys(daily[locId]).length === 0) delete daily[locId];
}
if (dailyChanged) await writeFile(dailyPath, JSON.stringify(daily));
}
if (rolled || pruned) console.log(` rollup: ${rolled} day-files -> daily averages, pruned ${pruned} old entries`);
}
main().catch((err) => {
console.error('Snapshot failed:', err);
process.exit(1);
});
-42
View File
@@ -1,42 +0,0 @@
// Curated source: hand-maintained known truck hubs (Milence, WattHub, ...).
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { PIPELINE_DATA_DIR } from '../paths.js';
import type { FreightSource } from './types.js';
import type { NormalizedFreightLocation } from '../types.js';
interface CuratedHub {
id: string;
name: string;
operatorName?: string;
city?: string;
address?: string;
lat: number;
lng: number;
maxPowerKw?: number;
isMegawatt?: boolean;
sourceUrl?: string;
}
export const curatedSource: FreightSource = {
id: 'curated',
async fetch(): Promise<NormalizedFreightLocation[]> {
const raw = await readFile(join(PIPELINE_DATA_DIR, 'curated-hubs.json'), 'utf-8');
const parsed = JSON.parse(raw) as { hubs: CuratedHub[] };
return (parsed.hubs ?? []).map((h) => ({
id: `curated:${h.id}`,
source: 'curated',
name: h.name,
address: h.address,
city: h.city,
lat: h.lat,
lng: h.lng,
operatorName: h.operatorName,
maxPowerKw: h.maxPowerKw ?? 0,
isMegawatt: h.isMegawatt ?? false,
sourceUrl: h.sourceUrl,
freightKind: 'dedicated',
freightReason: 'curated',
}));
},
};
-49
View File
@@ -1,49 +0,0 @@
// EAFO (European Alternative Fuels Observatory) source.
// EAFO has no stable per-location public JSON API, so this source reads an
// optional, periodically-refreshed static export checked into data/.
// Drop a file at data/eafo-nl-freight.json with shape: { locations: [...] }.
// If absent, the source logs and returns nothing (never fails the pipeline).
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { PIPELINE_DATA_DIR } from '../paths.js';
import type { FreightSource } from './types.js';
import type { NormalizedFreightLocation } from '../types.js';
interface EafoEntry {
id?: string | number;
name?: string;
operator?: string;
city?: string;
address?: string;
lat: number;
lng: number;
maxPowerKw?: number;
}
export const eafoSource: FreightSource = {
id: 'eafo',
async fetch(): Promise<NormalizedFreightLocation[]> {
let raw: string;
try {
raw = await readFile(join(PIPELINE_DATA_DIR, 'eafo-nl-freight.json'), 'utf-8');
} catch {
console.warn(' [eafo] no data/eafo-nl-freight.json export found — skipping EAFO');
return [];
}
const parsed = JSON.parse(raw) as { locations?: EafoEntry[] };
return (parsed.locations ?? [])
.filter((e) => Number.isFinite(e.lat) && Number.isFinite(e.lng))
.map((e, i) => ({
id: `eafo:${e.id ?? i}`,
source: 'eafo',
name: e.name ?? 'EAFO heavy-duty location',
address: e.address,
city: e.city,
lat: e.lat,
lng: e.lng,
operatorName: e.operator,
maxPowerKw: e.maxPowerKw ?? 0,
isMegawatt: (e.maxPowerKw ?? 0) >= 1000,
}));
},
};
-63
View File
@@ -1,63 +0,0 @@
// Merge + dedupe freight locations from multiple sources by rounded coordinates.
import type { NormalizedFreightLocation } from '../types.js';
// ~11 m grid. Tunable: higher precision = less merging.
const COORD_PRECISION = 4;
// Higher number = higher priority (kept on collision).
const SOURCE_PRIORITY: Record<string, number> = {
curated: 100,
ndw: 80,
eafo: 60,
ocm: 40,
};
function priority(source: string): number {
return SOURCE_PRIORITY[source] ?? 0;
}
function key(loc: NormalizedFreightLocation): string {
return `${loc.lat.toFixed(COORD_PRECISION)},${loc.lng.toFixed(COORD_PRECISION)}`;
}
export function mergeFreight(
groups: NormalizedFreightLocation[][],
): NormalizedFreightLocation[] {
const byCoord = new Map<string, NormalizedFreightLocation>();
for (const group of groups) {
for (const loc of group) {
const k = key(loc);
const existing = byCoord.get(k);
if (!existing) {
byCoord.set(k, { ...loc });
continue;
}
// Merge: keep the higher-priority record, take max power, prefer richer fields.
const winner = priority(loc.source) > priority(existing.source) ? loc : existing;
const other = winner === loc ? existing : loc;
const pickStatus =
winner.status && winner.status !== 'UNKNOWN' ? winner.status : other.status ?? winner.status;
const dedicated = winner.freightKind === 'dedicated' || other.freightKind === 'dedicated';
byCoord.set(k, {
...winner,
maxPowerKw: Math.max(winner.maxPowerKw, other.maxPowerKw),
isMegawatt: winner.isMegawatt || other.isMegawatt,
operatorName: winner.operatorName || other.operatorName,
address: winner.address || other.address,
city: winner.city || other.city,
status: pickStatus,
sourceUrl: winner.sourceUrl || other.sourceUrl,
priceKwh: winner.priceKwh ?? other.priceKwh,
freightKind: dedicated ? 'dedicated' : winner.freightKind ?? other.freightKind,
freightReason:
(winner.freightKind === 'dedicated' ? winner.freightReason : undefined) ??
(other.freightKind === 'dedicated' ? other.freightReason : undefined) ??
winner.freightReason ??
other.freightReason,
});
}
}
return [...byCoord.values()];
}
@@ -1,83 +0,0 @@
// Open Charge Map source. Requires a free API key (env OCM_API_KEY).
// Filters to high-power POIs (>= 150 kW) as a freight-capable heuristic.
import { join } from 'node:path';
import { readFile, writeFile, stat } from 'node:fs/promises';
import { CACHE_DIR } from '../paths.js';
import type { FreightSource } from './types.js';
import type { NormalizedFreightLocation } from '../types.js';
const OCM_MIN_KW = 150;
const CACHE_PATH = join(CACHE_DIR, 'ocm-nl.json');
const MAX_CACHE_AGE_MS = 24 * 60 * 60 * 1000;
interface OcmConnection {
PowerKW?: number;
LevelID?: number;
}
interface OcmPoi {
ID: number;
AddressInfo?: {
Title?: string;
AddressLine1?: string;
Town?: string;
Latitude: number;
Longitude: number;
};
OperatorInfo?: { Title?: string };
Connections?: OcmConnection[];
}
async function loadCached(refresh: boolean): Promise<OcmPoi[] | null> {
if (refresh) return null;
try {
const s = await stat(CACHE_PATH);
if (Date.now() - s.mtimeMs > MAX_CACHE_AGE_MS) return null;
return JSON.parse(await readFile(CACHE_PATH, 'utf-8')) as OcmPoi[];
} catch {
return null;
}
}
export const openChargeMapSource: FreightSource = {
id: 'ocm',
async fetch(refresh: boolean): Promise<NormalizedFreightLocation[]> {
const key = process.env.OCM_API_KEY;
let pois = await loadCached(refresh);
if (!pois) {
if (!key) {
console.warn(' [ocm] OCM_API_KEY not set and no fresh cache — skipping Open Charge Map');
return [];
}
const url =
`https://api.openchargemap.io/v3/poi/?countrycode=NL&maxresults=10000` +
`&compact=true&verbose=false&key=${encodeURIComponent(key)}`;
const res = await fetch(url, { headers: { Accept: 'application/json' } });
if (!res.ok) throw new Error(`OCM API ${res.status} ${res.statusText}`);
pois = (await res.json()) as OcmPoi[];
await writeFile(CACHE_PATH, JSON.stringify(pois));
}
const out: NormalizedFreightLocation[] = [];
for (const p of pois) {
const info = p.AddressInfo;
if (!info || !Number.isFinite(info.Latitude) || !Number.isFinite(info.Longitude)) continue;
const maxKw = Math.max(0, ...(p.Connections ?? []).map((c) => c.PowerKW ?? 0));
if (maxKw < OCM_MIN_KW) continue; // freight-capable heuristic
out.push({
id: `ocm:${p.ID}`,
source: 'ocm',
name: info.Title ?? 'Charging location',
address: info.AddressLine1,
city: info.Town,
lat: info.Latitude,
lng: info.Longitude,
operatorName: p.OperatorInfo?.Title,
maxPowerKw: Math.round(maxKw),
isMegawatt: maxKw >= 1000,
sourceUrl: `https://openchargemap.org/site/poi/details/${p.ID}`,
});
}
return out;
},
};
-8
View File
@@ -1,8 +0,0 @@
import type { NormalizedFreightLocation } from '../types.js';
// A modular external freight data source. Adding a source = implementing this
// interface and registering it in index.ts. A source that throws is skipped.
export interface FreightSource {
id: string;
fetch(refresh: boolean): Promise<NormalizedFreightLocation[]>;
}
-96
View File
@@ -1,96 +0,0 @@
// Resolve the currently-applicable €/kWh ENERGY price for a connector from its
// OCPI tariffs. NDW publishes the raw OCPI tariff structure (elements with
// price_components + restrictions). We pick, per the connector's power and the
// generation moment (Europe/Amsterdam local time), the cheapest applicable
// ENERGY price — that becomes the "current price" baked into the static data.
import type { OCPITariff, OCPITariffElement, OCPITariffRestrictions } from './types.js';
export interface ResolvedPrice {
price: number; // raw OCPI ENERGY price (the value operators advertise, ex-VAT per spec)
vat?: number; // VAT percentage, informational
}
// Sanity window: NDW carries placeholder values (0.01, 2.95, …). Anything
// outside a plausible public-charging band is treated as "no price".
const MIN_PLAUSIBLE = 0.05;
const MAX_PLAUSIBLE = 5.0;
interface NowParts {
date: string; // YYYY-MM-DD
hhmm: string; // HH:MM
weekday: string; // MONDAY … SUNDAY
}
const WEEKDAYS = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
// Break a Date into Europe/Amsterdam local parts for restriction matching.
export function nowParts(now: Date): NowParts {
const fmt = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Europe/Amsterdam',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
weekday: 'long',
hour12: false,
});
const parts = Object.fromEntries(fmt.formatToParts(now).map((p) => [p.type, p.value]));
const date = `${parts.year}-${parts.month}-${parts.day}`;
let hour = parts.hour ?? '00';
if (hour === '24') hour = '00';
return { date, hhmm: `${hour}:${parts.minute}`, weekday: (parts.weekday ?? '').toUpperCase() };
}
function matchesRestrictions(r: OCPITariffRestrictions | undefined, powerKw: number, t: NowParts): boolean {
if (!r) return true;
// Power band — only enforce when we actually know the connector's power
// (NDW omits max_electric_power for the majority of connectors).
if (powerKw > 0) {
if (r.min_power != null && powerKw < r.min_power) return false;
if (r.max_power != null && powerKw > r.max_power) return false;
}
// Day of week.
if (r.day_of_week && r.day_of_week.length && !r.day_of_week.includes(t.weekday)) return false;
// Date validity window.
if (r.start_date && t.date < r.start_date) return false;
if (r.end_date && t.date > r.end_date) return false;
// Time-of-day window (supports overnight ranges where start > end, and
// one-sided windows where only one bound is given).
const s = r.start_time ?? null;
const e = r.end_time ?? null;
if (s && e) {
const within = s <= e ? t.hhmm >= s && t.hhmm <= e : t.hhmm >= s || t.hhmm <= e;
if (!within) return false;
} else if (s) {
if (t.hhmm < s) return false;
} else if (e) {
if (t.hhmm > e) return false;
}
return true;
}
function energyPriceFromElement(el: OCPITariffElement): ResolvedPrice | null {
const ec = el.price_components?.find((pc) => pc.type === 'ENERGY');
if (!ec || typeof ec.price !== 'number') return null;
if (ec.price < MIN_PLAUSIBLE || ec.price > MAX_PLAUSIBLE) return null;
return { price: ec.price, vat: ec.vat };
}
// Cheapest currently-applicable ENERGY price across all of a connector's tariffs.
export function resolveConnectorPrice(tariffs: OCPITariff[], powerKw: number, now: Date): ResolvedPrice | null {
const t = nowParts(now);
let best: ResolvedPrice | null = null;
for (const tariff of tariffs) {
for (const el of tariff.elements ?? []) {
if (!matchesRestrictions(el.restrictions, powerKw, t)) continue;
const p = energyPriceFromElement(el as OCPITariffElement);
if (p && (!best || p.price < best.price)) best = p;
}
}
return best;
}
-195
View File
@@ -1,195 +0,0 @@
// Shared types for the data pipeline.
// OCPI interfaces mirror the NDW open-data feed (adapted from fleetsim's import script).
export interface OCPICoordinates {
latitude: string;
longitude: string;
}
export interface OCPIConnector {
id: string;
standard: string;
format: string;
power_type: string;
max_voltage?: number;
max_amperage?: number;
max_electric_power?: number; // watts
tariff_ids?: string[];
last_updated: string;
}
export interface OCPIEVSE {
uid: string;
evse_id: string;
status: string;
capabilities?: string[];
connectors: OCPIConnector[];
physical_reference?: string;
floor_level?: string;
coordinates?: OCPICoordinates;
last_updated: string;
}
export interface OCPIParty {
name: string;
website?: string;
logo?: { url: string };
}
export interface OCPILocation {
country_code: string;
party_id: string;
id: string;
publish: boolean;
name?: string;
address: string;
city: string;
postal_code?: string;
state?: string;
country: string;
coordinates: OCPICoordinates;
parking_type?: string;
evses?: OCPIEVSE[];
operator: OCPIParty;
owner?: OCPIParty;
suboperator?: OCPIParty;
time_zone?: string;
opening_times?: { twentyfourseven?: boolean };
charging_when_closed?: boolean;
last_updated: string;
}
export interface OCPIPriceComponent {
type: string; // ENERGY | TIME | FLAT | PARKING_TIME | ...
price: number;
vat?: number;
step_size?: number;
}
export interface OCPITariffRestrictions {
start_time?: string | null; // HH:MM (local)
end_time?: string | null;
start_date?: string | null; // YYYY-MM-DD
end_date?: string | null;
min_kwh?: number | null;
max_kwh?: number | null;
min_power?: number | null; // kW
max_power?: number | null;
min_duration?: number | null;
max_duration?: number | null;
day_of_week?: string[] | null;
reservation?: string | null;
}
export interface OCPITariffElement {
price_components?: OCPIPriceComponent[];
restrictions?: OCPITariffRestrictions;
}
export interface OCPITariff {
id: string;
country_code: string;
party_id: string;
currency: string;
type?: string;
min_price?: number;
max_price?: number;
elements: OCPITariffElement[];
start_date_time?: string;
end_date_time?: string;
last_updated: string;
}
export type ChargeCategory = 'passenger' | 'freight';
// 'dedicated' = explicit truck facility (operator/name/MCS/curated);
// 'hpc' = only qualifies on raw DC power >= 350 kW (truck-capable, not necessarily truck-accessible).
export type FreightKind = 'dedicated' | 'hpc';
export type FreightReason = 'operator' | 'truck-name' | 'mcs' | 'depot-name' | 'motorway' | 'power' | 'curated';
// Classification metadata derived from a location's connectors.
export interface ClassificationMeta {
category: ChargeCategory;
maxPowerKw: number;
hasCCS: boolean;
hasMCS: boolean;
isMegawatt: boolean;
dcCount: number;
freightKind?: FreightKind;
freightReason?: FreightReason;
}
// Aggregate availability derived from a location's EVSE statuses (fleetsim-style).
export type AggregateStatus = 'AVAILABLE' | 'CHARGING' | 'UNAVAILABLE' | 'UNKNOWN';
// Lightweight, "without details" point as written into crop-out / national files.
export interface LightLocation {
locationId: string; // sanitized, URL-safe id (shared with detail bundle key)
ocpiId?: string;
name: string;
address?: string;
city?: string;
operatorName?: string;
lat: number;
lng: number;
layer: ChargeCategory;
maxPowerKw: number;
isMegawatt: boolean;
status: AggregateStatus;
source: string; // 'ndw' | 'curated' | 'eafo' | 'ocm'
sourceUrl?: string;
priceKwh?: number; // cheapest currently-applicable €/kWh across this location's connectors
freightKind?: FreightKind;
freightReason?: FreightReason;
}
// Normalized external freight location (from sources/*).
export interface NormalizedFreightLocation {
id: string;
source: string;
name: string;
address?: string;
city?: string;
lat: number;
lng: number;
operatorName?: string;
maxPowerKw: number;
isMegawatt?: boolean;
status?: AggregateStatus;
sourceUrl?: string;
priceKwh?: number;
freightKind?: FreightKind;
freightReason?: FreightReason;
}
// Full enriched location detail ("with details"), stored in per-gemeente bundles.
export interface EnrichedConnector extends OCPIConnector {
tariffs: OCPITariff[];
priceKwh?: number; // resolved current €/kWh ENERGY price
priceVat?: number; // VAT %, informational
}
export interface EnrichedEVSE extends Omit<OCPIEVSE, 'connectors'> {
connectors: EnrichedConnector[];
}
export interface EnrichedLocation {
locationId: string;
ocpiId: string;
name: string;
address: string;
city: string;
postalCode?: string;
country: string;
latitude: number;
longitude: number;
parkingType?: string;
operatorName: string;
operatorWebsite?: string;
ownerName?: string;
twentyFourSeven: boolean;
lastUpdated: string;
layer: ChargeCategory;
maxPowerKw: number;
freightKind?: FreightKind;
freightReason?: FreightReason;
evses: EnrichedEVSE[];
}
-189
View File
@@ -1,189 +0,0 @@
// Write all static artifacts into webapp/public/.
import { mkdir, writeFile, rm, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { DATA_DIR, GEMEENTEN_DIR, MUNICIPALITIES_JSON, PIPELINE_DATA_DIR } from './paths.js';
import { slugify } from './slugify.js';
import type { Boundaries, BoundaryFeature } from './fetchBoundaries.js';
import { GemeenteAssigner } from './assignGemeente.js';
import type { LightLocation, EnrichedLocation } from './types.js';
interface SeedMunicipality {
name: string;
slug: string;
province: string;
population: number;
code: string | null;
}
interface WriteInput {
passengerLights: LightLocation[];
freightLights: LightLocation[];
enrichedById: Map<string, EnrichedLocation>;
boundaries: Boundaries;
generatedAt: string;
}
function pointFeature(l: LightLocation) {
return {
type: 'Feature' as const,
geometry: { type: 'Point' as const, coordinates: [l.lng, l.lat] },
properties: {
type: 'charge',
layer: l.layer,
locationId: l.locationId,
name: l.name,
address: l.address ?? '',
city: l.city ?? '',
operatorName: l.operatorName ?? '',
maxPowerKw: l.maxPowerKw,
isMegawatt: l.isMegawatt,
status: l.status,
source: l.source,
...(l.priceKwh != null ? { priceKwh: l.priceKwh } : {}),
...(l.freightKind ? { freightKind: l.freightKind } : {}),
...(l.freightReason ? { freightReason: l.freightReason } : {}),
},
};
}
function boundaryFeature(g: BoundaryFeature) {
return {
type: 'Feature' as const,
geometry: g.geometry,
properties: { type: 'boundary', gemeente: g.properties.statnaam, code: g.properties.statcode },
};
}
export async function writeOutputs(input: WriteInput): Promise<void> {
const { passengerLights, freightLights, enrichedById, boundaries, generatedAt } = input;
console.log('Writing outputs...');
// Fresh gemeenten dir.
await rm(GEMEENTEN_DIR, { recursive: true, force: true });
await mkdir(GEMEENTEN_DIR, { recursive: true });
const assigner = new GemeenteAssigner(boundaries);
const seed = JSON.parse(await readFile(join(PIPELINE_DATA_DIR, 'municipalities-seed.json'), 'utf-8')) as SeedMunicipality[];
const seedByCode = new Map<string, SeedMunicipality>();
for (const m of seed) if (m.code) seedByCode.set(m.code, m);
// Group lights by gemeente code.
const byGemeente = new Map<string, LightLocation[]>();
let unassigned = 0;
let viaFallback = 0;
for (const l of [...passengerLights, ...freightLights]) {
const res = assigner.assignWithFallback(l);
if (!res) {
unassigned++;
continue;
}
if (res.fallback) viaFallback++;
let arr = byGemeente.get(res.code);
if (!arr) byGemeente.set(res.code, (arr = []));
arr.push(l);
}
console.log(
` assigned points; ${viaFallback} via nearest-gemeente fallback, ${unassigned} unassigned (kept in national files only)`,
);
// Per-gemeente crop-out + detail bundle.
const municipalities: Array<SeedMunicipality & { passengerCount: number; freightCount: number }> = [];
const slugByCode = new Map<string, string>();
for (const g of boundaries.gemeenten) {
const code = g.properties.statcode;
const name = g.properties.statnaam;
const slug = slugify(name);
slugByCode.set(code, slug);
const lights = byGemeente.get(code) ?? [];
const passengerCount = lights.filter((l) => l.layer === 'passenger').length;
const freightCount = lights.filter((l) => l.layer === 'freight').length;
const bounds = boundaries.gemeenteBboxes.get(code) ?? [0, 0, 0, 0];
const operators = [...new Set(lights.map((l) => l.operatorName).filter(Boolean))].sort() as string[];
const cropout = {
type: 'FeatureCollection' as const,
metadata: {
gemeente: name,
slug,
code,
generated_at: generatedAt,
total_passenger: passengerCount,
total_freight: freightCount,
bounds,
operators,
},
features: [...lights.map(pointFeature), boundaryFeature(g)],
};
// Detail bundle: enriched details for the lights in this gemeente that have them.
const details: Record<string, EnrichedLocation> = {};
for (const l of lights) {
const d = enrichedById.get(l.locationId);
if (d) details[l.locationId] = d;
}
await writeFile(join(GEMEENTEN_DIR, `${slug}.geojson`), JSON.stringify(cropout));
await writeFile(join(GEMEENTEN_DIR, `${slug}.details.json`), JSON.stringify(details));
const sm = seedByCode.get(code);
municipalities.push({
name,
slug,
province: sm?.province ?? '',
population: sm?.population ?? 0,
code,
passengerCount,
freightCount,
});
}
// National lightweight files (every point, no details), split by layer.
await writeFile(
join(DATA_DIR, 'nederland-passenger.geojson'),
JSON.stringify({
type: 'FeatureCollection',
metadata: { generated_at: generatedAt, layer: 'passenger', total: passengerLights.length },
features: passengerLights.map(pointFeature),
}),
);
await writeFile(
join(DATA_DIR, 'nederland-freight.geojson'),
JSON.stringify({
type: 'FeatureCollection',
metadata: { generated_at: generatedAt, layer: 'freight', total: freightLights.length },
features: freightLights.map(pointFeature),
}),
);
// Province boundaries.
await writeFile(
join(DATA_DIR, 'provinces.geojson'),
JSON.stringify({
type: 'FeatureCollection',
metadata: { generated_at: generatedAt },
features: boundaries.provinces.map(boundaryFeature),
}),
);
// municipalities.json: Nederland (total) first, then gemeenten alphabetical.
municipalities.sort((a, b) => a.name.localeCompare(b.name));
const totalPassenger = passengerLights.length;
const totalFreight = freightLights.length;
const nederland = {
name: 'Nederland (totaal)',
slug: 'nederland',
province: 'Alle provincies',
population: 17561268,
code: null,
passengerCount: totalPassenger,
freightCount: totalFreight,
};
await writeFile(MUNICIPALITIES_JSON, JSON.stringify([nederland, ...municipalities], null, 2));
console.log(
` wrote ${municipalities.length} gemeente crop-outs + detail bundles, ` +
`national files (${totalPassenger} passenger / ${totalFreight} freight), provinces, municipalities.json`,
);
}
-14
View File
@@ -1,14 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"noEmit": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}
+6
View File
@@ -0,0 +1,6 @@
services:
laadpalenviewer:
build: .
ports:
- "8104:8000"
restart: unless-stopped
+108
View File
@@ -0,0 +1,108 @@
import httpx
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI(title="Laadpalenviewer")
CHARGEMAP_URL = "https://api.openchargemap.io/v3/poi/"
async def fetch_charge_points():
async with httpx.AsyncClient(timeout=30.0) as client:
try:
resp = await client.get(CHARGEMAP_URL, params={
"countrycode": "NL",
"maxresults": 500,
"compact": "true",
"verbose": "false",
})
resp.raise_for_status()
raw = resp.json()
except Exception:
raw = []
points = []
for item in raw:
try:
lat = float(item.get("Latitude", 0))
lon = float(item.get("Longitude", 0))
except (ValueError, TypeError):
continue
if not lat or not lon:
continue
refs = item.get("OperatorInfo") or {}
operator = refs.get("Title", "Unknown")
status = item.get("StatusType") or {}
status_name = status.get("Title", "Unknown")
level = item.get("Level") or {}
power = level.get("Title", "")
points.append({
"lat": lat, "lon": lon,
"name": (item.get("AddressInfo") or {}).get("Title", "Charge Point"),
"operator": operator,
"status": status_name,
"power": power,
"connections": len(item.get("Connections") or []),
})
return points
@app.get("/api/charges")
async def get_charges():
points = await fetch_charge_points()
return {"count": len(points), "points": points}
@app.get("/", response_class=HTMLResponse)
async def root():
return """<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laadpalenviewer - Laadpunten in Nederland</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,sans-serif}
#map{width:100%;height:100vh}
.stats-bar{position:absolute;top:10px;right:10px;z-index:1000;background:white;border-radius:8px;padding:12px 16px;box-shadow:0 2px 10px rgba(0,0,0,.1)}
.stat-value{font-size:20px;font-weight:700}
.stat-label{font-size:11px;color:#888}
.legend{position:absolute;bottom:30px;right:10px;z-index:1000;background:white;border-radius:8px;padding:12px;box-shadow:0 2px 10px rgba(0,0,0,.1)}
.legend h3{font-size:13px;margin-bottom:8px}
.legend-item{display:flex;align-items:center;gap:8px;font-size:12px;margin:4px 0}
.legend-dot{width:12px;height:12px;border-radius:50%}
</style>
</head>
<body>
<div id="map"></div>
<div class="stats-bar">
<div><div class="stat-value" id="total">-</div><div class="stat-label">Laadpunten</div></div>
</div>
<div class="legend">
<h3>Status</h3>
<div class="legend-item"><div class="legend-dot" style="background:#22c55e"></div> Beschikbaar</div>
<div class="legend-item"><div class="legend-dot" style="background:#f59e0b"></div> Bezet</div>
<div class="legend-item"><div class="legend-dot" style="background:#ef4444"></div> Niet beschikbaar</div>
</div>
<script>
const map = L.map("map").setView([52.1, 5.3], 8);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {attribution: "OpenStreetMap"}).addTo(map);
const sc = {Operational:"#22c55e",Available:"#22c55e","Partly Operational":"#f59e0b",Busy:"#f59e0b","Out of Service":"#ef4444","Non Operational":"#ef4444"};
async function load() {
const r = await fetch("/api/charges");
const d = await r.json();
document.getElementById("total").textContent = d.count;
d.points.forEach(p => {
L.circleMarker([p.lat, p.lon], {radius:6,fillColor:sc[p.status]||"#666",color:"#fff",weight:1,fillOpacity:0.9}).addTo(map)
.bindPopup("<b>"+p.name+"</b><br>"+p.operator+"<br>Status: "+p.status);
});
}
load();
</script>
</body>
</html>"""
+3
View File
@@ -0,0 +1,3 @@
fastapi==0.115.0
uvicorn==0.30.0
httpx==0.27.0
-9
View File
@@ -1,9 +0,0 @@
/node_modules
/.next
/out
/build
next-env.d.ts
.DS_Store
*.tsbuildinfo
.vercel
.env*.local
-255
View File
@@ -1,255 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
/**
* Geocoding API proxy for PDOK Locatieserver
*
* This endpoint proxies requests to the PDOK (Publieke Dienstverlening Op de Kaart)
* Locatieserver API, which provides geocoding and address lookup services for
* the Netherlands.
*
* Benefits of using a proxy:
* - Hides API details from client
* - Bypasses CSP restrictions
* - Allows server-side rate limiting
* - Can add caching if needed
*/
// Simple in-memory rate limiting
const rateLimitStore = new Map<string, { count: number; resetTime: number }>();
const RATE_LIMIT = 30; // requests per minute
const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
interface PDOKSuggestion {
weergavenaam: string; // Display name (e.g., "Kalverstraat 1, Amsterdam")
id: string;
type: string; // Type (e.g., "adres", "weg", "plaats")
score: number;
centroide_ll?: string; // "POINT(lon lat)"
gemeentenaam?: string; // Municipality name
}
interface PDOKLookupResult {
weergavenaam: string;
centroide_ll: string;
gemeentenaam: string;
straatnaam?: string;
huisnummer?: string;
postcode?: string;
woonplaatsnaam?: string;
}
function checkRateLimit(ip: string): boolean {
const now = Date.now();
const record = rateLimitStore.get(ip);
if (!record || now > record.resetTime) {
rateLimitStore.set(ip, {
count: 1,
resetTime: now + RATE_LIMIT_WINDOW,
});
return true;
}
if (record.count >= RATE_LIMIT) {
return false;
}
record.count++;
return true;
}
export async function GET(request: NextRequest) {
try {
// Get client IP for rate limiting
const ip =
request.headers.get('x-forwarded-for') ||
request.headers.get('x-real-ip') ||
'unknown';
// Check rate limit
if (!checkRateLimit(ip)) {
return new NextResponse(
JSON.stringify({
error: 'Rate limit exceeded',
message: `Maximum ${RATE_LIMIT} requests per minute`,
}),
{
status: 429,
headers: {
'Content-Type': 'application/json',
'Retry-After': String(RATE_LIMIT_WINDOW / 1000),
},
}
);
}
// Get query parameters
const searchParams = request.nextUrl.searchParams;
const query = searchParams.get('q');
const id = searchParams.get('id'); // For lookup after selection
const lat = searchParams.get('lat'); // For reverse geocoding
const lon = searchParams.get('lon');
if (!query && !id && !(lat && lon)) {
return new NextResponse(
JSON.stringify({
error: 'Missing parameter',
message: 'Provide "q" (query), "id" (lookup), or "lat"+"lon" (reverse)',
}),
{
status: 400,
headers: {
'Content-Type': 'application/json',
},
}
);
}
// Reverse geocoding: nearest address for a coordinate
if (lat && lon) {
const latNum = parseFloat(lat);
const lonNum = parseFloat(lon);
if (!Number.isFinite(latNum) || !Number.isFinite(lonNum)) {
return new NextResponse(
JSON.stringify({ error: 'Invalid coordinates' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
const reverseUrl = `https://api.pdok.nl/bzk/locatieserver/search/v3_1/reverse?lat=${latNum}&lon=${lonNum}&rows=1&type=adres&fl=*`;
const response = await fetch(reverseUrl, { headers: { Accept: 'application/json' } });
if (!response.ok) {
throw new Error(`PDOK reverse API error: ${response.status}`);
}
const data = await response.json();
const doc = data.response?.docs?.[0];
if (!doc) {
return new NextResponse(
JSON.stringify({ error: 'Not found', message: 'No address near this location' }),
{ status: 404, headers: { 'Content-Type': 'application/json' } }
);
}
const centroidMatch = doc.centroide_ll?.match(/POINT\(([\d.]+) ([\d.]+)\)/);
const coordinates = centroidMatch
? {
longitude: parseFloat(centroidMatch[1]),
latitude: parseFloat(centroidMatch[2]),
}
: { longitude: lonNum, latitude: latNum };
return NextResponse.json({
id: doc.id,
displayName: doc.weergavenaam,
municipality: doc.gemeentenaam,
street: doc.straatnaam,
houseNumber: doc.huisnummer,
postalCode: doc.postcode,
city: doc.woonplaatsnaam,
coordinates,
});
}
// If ID provided, do a lookup (get full details for selected suggestion)
if (id) {
const lookupUrl = `https://api.pdok.nl/bzk/locatieserver/search/v3_1/lookup?id=${encodeURIComponent(id)}&fl=*`;
const response = await fetch(lookupUrl, {
headers: {
'Accept': 'application/json',
},
});
if (!response.ok) {
throw new Error(`PDOK API error: ${response.status}`);
}
const data = await response.json();
const doc = data.response?.docs?.[0];
if (!doc) {
return new NextResponse(
JSON.stringify({
error: 'Not found',
message: 'Address not found',
}),
{
status: 404,
headers: {
'Content-Type': 'application/json',
},
}
);
}
// Parse centroid coordinates
const centroidMatch = doc.centroide_ll?.match(/POINT\(([\d.]+) ([\d.]+)\)/);
const coordinates = centroidMatch
? {
longitude: parseFloat(centroidMatch[1]),
latitude: parseFloat(centroidMatch[2]),
}
: null;
return NextResponse.json({
id: doc.id,
displayName: doc.weergavenaam,
municipality: doc.gemeentenaam,
street: doc.straatnaam,
houseNumber: doc.huisnummer,
postalCode: doc.postcode,
city: doc.woonplaatsnaam,
coordinates,
});
}
// Otherwise, do a suggest (autocomplete search)
const suggestUrl = `https://api.pdok.nl/bzk/locatieserver/search/v3_1/suggest?q=${encodeURIComponent(
query!
)}&rows=10`;
const response = await fetch(suggestUrl, {
headers: {
'Accept': 'application/json',
},
});
if (!response.ok) {
throw new Error(`PDOK API error: ${response.status}`);
}
const data = await response.json();
const suggestions = data.response?.docs || [];
// Transform PDOK response to simpler format
const results = suggestions.map((doc: PDOKSuggestion) => ({
id: doc.id,
displayName: doc.weergavenaam,
type: doc.type,
municipality: doc.gemeentenaam,
score: doc.score,
}));
return NextResponse.json({
query: query,
results,
});
} catch (error) {
console.error('Geocoding error:', error);
return new NextResponse(
JSON.stringify({
error: 'Internal server error',
message: 'Failed to fetch geocoding results',
}),
{
status: 500,
headers: {
'Content-Type': 'application/json',
},
}
);
}
}
-72
View File
@@ -1,72 +0,0 @@
"use client";
import { useEffect, useState, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import dynamic from "next/dynamic";
import {
CropoutData,
ChargeFeature,
BoundaryFeature,
DEFAULT_FILTERS,
} from "@/types/charging";
const MapDeck = dynamic(() => import("@/components/MapDeck"), { ssr: false });
const NL_BOUNDS: [number, number, number, number] = [3.31, 50.75, 7.21, 53.47];
function EmbedInner() {
const params = useSearchParams();
const raw = params.get("gemeente");
const slug = raw === "alle-gemeenten" ? "nederland" : raw || "utrecht";
const [chargeFeatures, setChargeFeatures] = useState<ChargeFeature[]>([]);
const [boundaryFeatures, setBoundaryFeatures] = useState<BoundaryFeature[]>([]);
const [bounds, setBounds] = useState<[number, number, number, number] | null>(null);
const [selected, setSelected] = useState<ChargeFeature | null>(null);
useEffect(() => {
let cancelled = false;
const load = async () => {
if (slug === "nederland") {
const [p, f] = (await Promise.all([
fetch("/data/nederland-passenger.geojson").then((r) => r.json()),
fetch("/data/nederland-freight.geojson").then((r) => r.json()),
])) as CropoutData[];
if (cancelled) return;
setChargeFeatures([...(p.features as ChargeFeature[]), ...(f.features as ChargeFeature[])]);
setBounds(NL_BOUNDS);
} else {
const crop = (await fetch(`/data/gemeenten/${slug}.geojson`).then((r) => r.json())) as CropoutData;
if (cancelled) return;
setChargeFeatures(crop.features.filter((f) => f.properties.type === "charge") as ChargeFeature[]);
setBoundaryFeatures(crop.features.filter((f) => f.properties.type === "boundary") as BoundaryFeature[]);
setBounds(crop.metadata.bounds ?? null);
}
};
load().catch((e) => console.error(e));
return () => {
cancelled = true;
};
}, [slug]);
return (
<div className="h-screen w-screen">
<MapDeck
chargeFeatures={chargeFeatures}
boundaryFeatures={boundaryFeatures}
bounds={bounds}
filters={DEFAULT_FILTERS}
selectedLocationId={selected?.properties.locationId ?? null}
onSelect={setSelected}
/>
</div>
);
}
export default function EmbedPage() {
return (
<Suspense fallback={<div className="h-screen w-screen flex items-center justify-center text-gray-500">Kaart laden…</div>}>
<EmbedInner />
</Suspense>
);
}
-34
View File
@@ -1,34 +0,0 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
/* MapLibre popup tweaks */
.maplibregl-popup-content {
padding: 0;
border-radius: 0.5rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.scrollbar-hide {
-ms-overflow-style: none;
scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
-37
View File
@@ -1,37 +0,0 @@
import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { Analytics } from "@vercel/analytics/react";
import "./globals.css";
const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] });
const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] });
export const metadata: Metadata = {
title: "Laadpalenviewer - Laadpunten voor personenauto's en logistiek in Nederland",
description:
"Interactieve kaart van laadpunten in Nederland: personenauto-laadpunten (NDW OCPI) en logistieke/vracht-laadpunten (Milence, WattHub, megawatt charging) per gemeente, met gemeente- en provinciegrenzen van PDOK/CBS.",
openGraph: {
title: "Laadpalenviewer",
description:
"Laadpunten voor personenauto's en logistiek/vracht in Nederland op een interactieve kaart per gemeente.",
type: "website",
locale: "nl_NL",
},
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
viewportFit: "cover",
};
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="nl">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
{children}
<Analytics />
</body>
</html>
);
}
-489
View File
@@ -1,489 +0,0 @@
"use client";
import { useState, useEffect, useMemo, useRef } from "react";
import dynamic from "next/dynamic";
import MunicipalitySelector from "@/components/MunicipalitySelector";
import AddressSearchInput from "@/components/AddressSearchInput";
import FilterPanel from "@/components/FilterPanel";
import StatsPanel from "@/components/StatsPanel";
import LocationDetailPanel from "@/components/LocationDetailPanel";
import LayerSwitcher from "@/components/LayerSwitcher";
import GemeenteScorecard from "@/components/GemeenteScorecard";
import AboutModal from "@/components/AboutModal";
import ShareModal from "@/components/ShareModal";
import GuidedTour, { type TourStep } from "@/components/GuidedTour";
import type { ChoroplethData, AreaProps } from "@/types/analysis";
import { findGemeenteSlug } from "@/lib/pointInGemeente";
import {
Municipality,
CropoutData,
DetailBundle,
ChargeFeature,
BoundaryFeature,
Filters,
DEFAULT_FILTERS,
} from "@/types/charging";
const MapDeck = dynamic(() => import("@/components/MapDeck"), {
ssr: false,
loading: () => (
<div className="w-full h-full flex items-center justify-center bg-gray-100">
<p className="text-gray-500">Kaart laden…</p>
</div>
),
});
const NL_BOUNDS: [number, number, number, number] = [3.31, 50.75, 7.21, 53.47];
const DEFAULT_SLUG = "utrecht";
export default function Home() {
const [municipalities, setMunicipalities] = useState<Municipality[]>([]);
const [selectedMunicipality, setSelectedMunicipality] = useState<string>("");
const [chargeFeatures, setChargeFeatures] = useState<ChargeFeature[]>([]);
const [boundaryFeatures, setBoundaryFeatures] = useState<BoundaryFeature[]>([]);
const [bounds, setBounds] = useState<[number, number, number, number] | null>(null);
const [details, setDetails] = useState<DetailBundle>({});
const [gemeenteName, setGemeenteName] = useState<string>("");
const [loading, setLoading] = useState(false);
const [filters, setFilters] = useState<Filters>(DEFAULT_FILTERS);
const [selected, setSelected] = useState<ChargeFeature | null>(null);
const [showAbout, setShowAbout] = useState(false);
const [showShare, setShowShare] = useState(false);
const [showTutorial, setShowTutorial] = useState(false);
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const [choropleth, setChoropleth] = useState<ChoroplethData | null>(null);
const [analysisMetric, setAnalysisMetric] = useState<string | null>(null);
const [selectedArea, setSelectedArea] = useState<AreaProps | null>(null);
const isNational = selectedMunicipality === "nederland";
// Load the analysis choropleth dataset once.
useEffect(() => {
fetch("/data/derived/gemeente-metrics.geojson")
.then((r) => (r.ok ? r.json() : null))
.then((d: ChoroplethData | null) => d && setChoropleth(d))
.catch(() => {});
}, []);
const metricMeta = useMemo(
() => choropleth?.metadata.metrics.find((m) => m.key === analysisMetric) ?? null,
[choropleth, analysisMetric],
);
const choroActive = isNational && !!analysisMetric;
// Refs so the guided tour can read current data inside its step actions.
const chargeFeaturesRef = useRef(chargeFeatures);
const choroplethRef = useRef(choropleth);
useEffect(() => {
chargeFeaturesRef.current = chargeFeatures;
}, [chargeFeatures]);
useEffect(() => {
choroplethRef.current = choropleth;
}, [choropleth]);
// Interactive guided tour: each step drives the app to a real example screen,
// lets the existing zoom/fit behaviour kick in, and spotlights the relevant UI.
const tourSteps: TourStep[] = useMemo(
() => [
{
title: "Welkom bij Laadpalenviewer",
body: (
<>
<p>Een korte rondleiding stuurt je langs alle onderdelen — de kaart beweegt mee.</p>
<p className="text-gray-400">Later opnieuw te openen via de knop “Uitleg”.</p>
</>
),
action: () => {
setSelected(null);
setSelectedArea(null);
setAnalysisMetric(null);
setSelectedMunicipality("utrecht");
},
},
{
title: "Kies een gemeente",
target: '[data-tour="municipality"]',
body: <p>Selecteer hier een gemeente of zoek een adres. De kaart zoomt naar die gemeente en laadt alle details.</p>,
},
{
title: "Twee kaartlagen + filters",
target: '[data-tour="layers"]',
body: (
<p>
Zet de lagen <strong>personenauto</strong> en <strong>logistiek/vracht</strong> aan/uit en filter op
vermogen. De ⓘ-iconen geven overal extra uitleg.
</p>
),
},
{
title: "Kleuren = live status",
target: '[data-tour="legend"]',
body: (
<p>
Punten zijn gekleurd op OCPI-status uit de uurlijkse momentopname:
<span className="text-green-600"> beschikbaar</span>,
<span className="text-blue-600"> bezet</span>,
<span className="text-red-600"> niet beschikbaar</span>.
</p>
),
},
{
title: "Detail van een laadpunt",
target: '[data-tour="detail"]',
action: () => {
const f = chargeFeaturesRef.current.find((x) => x.properties.layer === "passenger") ?? chargeFeaturesRef.current[0];
if (f) setSelected(f);
},
body: <p>We openden een voorbeeld-laadpunt: exploitant, connectoren (type &amp; kW) en tarieven — direct geladen.</p>,
},
{
title: "Gebruik over de tijd",
target: '[data-tour="usage"]',
body: <p>Per uur het aandeel connectoren dat laadt (24u/7d/30d/1j), opgebouwd uit de uurlijkse snapshots.</p>,
},
{
title: "Analyse per gemeente",
target: '[data-tour="analyse"]',
action: () => {
setSelected(null);
setSelectedMunicipality("nederland");
setAnalysisMetric("siting_priority");
},
body: (
<p>
In de landelijke weergave kleurt elke indicator de gemeenten (choropleth). Hier:
<strong> plaatsingsprioriteit</strong>. Onder de keuze staat steeds een uitleg.
</p>
),
},
{
title: "Gemeente-scorecard",
target: '[data-tour="scorecard"]',
action: () => {
const fc = choroplethRef.current;
const f =
fc?.features.find((x) => x.properties.gemeente === "Utrecht") ?? fc?.features.find((x) => x.properties.chargers_total != null);
if (f) setSelectedArea(f.properties as typeof selectedArea);
},
body: (
<p>
Klik een gemeente voor de scorecard: verwachte vraag (peer-model), tekort/overschot, live belasting en
een netimpact-scenario met schuiven.
</p>
),
},
{
title: "Bronnen & methodologie",
body: (
<>
<p>
Bronnen: NDW DOT-NL, CBS, PDOK, Open Charge Map. Vermogen wordt aangenomen (NDW mist het meestal);
congestie is gemodelleerd.
</p>
<p className="text-gray-400">Volledige uitleg staat onder “Over”.</p>
</>
),
action: () => {
setSelectedArea(null);
},
},
],
[],
);
// Load municipalities once.
useEffect(() => {
fetch("/municipalities.json")
.then((r) => r.json())
.then((data: Municipality[]) => {
const sorted = data.sort((a, b) => {
if (a.slug === "nederland") return 1;
if (b.slug === "nederland") return -1;
return a.name.localeCompare(b.name);
});
setMunicipalities(sorted);
const params = new URLSearchParams(window.location.search);
const raw = params.get("gemeente");
const param = raw === "alle-gemeenten" ? "nederland" : raw;
const last = localStorage.getItem("lastSelectedMunicipality");
if (param && sorted.find((m) => m.slug === param)) setSelectedMunicipality(param);
else if (last && sorted.find((m) => m.slug === last)) setSelectedMunicipality(last);
else setSelectedMunicipality(sorted.find((m) => m.slug === DEFAULT_SLUG) ? DEFAULT_SLUG : sorted[0].slug);
})
.catch((e) => console.error("municipalities load failed", e));
}, []);
// Persist selection to URL + localStorage.
useEffect(() => {
if (!selectedMunicipality || municipalities.length === 0) return;
localStorage.setItem("lastSelectedMunicipality", selectedMunicipality);
const url = new URL(window.location.href);
url.searchParams.set("gemeente", isNational ? "alle-gemeenten" : selectedMunicipality);
window.history.replaceState({}, "", url.toString());
}, [selectedMunicipality, municipalities, isNational]);
// A locationId to re-select once the next gemeente load finishes (used by the
// "jump to gemeente" action in the detail panel from the national view).
const pendingSelectRef = useRef<string | null>(null);
// Load data when municipality changes.
useEffect(() => {
if (!selectedMunicipality) return;
let cancelled = false;
setLoading(true);
setSelected(null);
const load = async () => {
if (selectedMunicipality === "nederland") {
const [pRes, fRes, provRes] = await Promise.all([
fetch("/data/nederland-passenger.geojson"),
fetch("/data/nederland-freight.geojson"),
fetch("/data/provinces.geojson"),
]);
const [p, f, prov] = (await Promise.all([pRes.json(), fRes.json(), provRes.json()])) as CropoutData[];
if (cancelled) return;
setChargeFeatures([
...(p.features as ChargeFeature[]),
...(f.features as ChargeFeature[]),
]);
setBoundaryFeatures(prov.features as BoundaryFeature[]);
setBounds(NL_BOUNDS);
setDetails({});
setGemeenteName("Nederland");
} else {
const [cropRes, detRes, statusRes] = await Promise.all([
fetch(`/data/gemeenten/${selectedMunicipality}.geojson`),
fetch(`/data/gemeenten/${selectedMunicipality}.details.json`),
fetch(`/data/status/${selectedMunicipality}.json`),
]);
const crop = (await cropRes.json()) as CropoutData;
const bundle = (await detRes.json()) as DetailBundle;
// Fresh hourly status (may not exist yet); overrides build-time status on the map.
const freshStatus = statusRes.ok
? ((await statusRes.json()) as Record<string, ChargeFeature["properties"]["status"]>)
: {};
if (cancelled) return;
const charges = (crop.features.filter((f) => f.properties.type === "charge") as ChargeFeature[]).map((f) => {
const s = freshStatus[f.properties.locationId];
return s ? { ...f, properties: { ...f.properties, status: s } } : f;
});
const boundaries = crop.features.filter((f) => f.properties.type === "boundary") as BoundaryFeature[];
setChargeFeatures(charges);
setBoundaryFeatures(boundaries);
setBounds(crop.metadata.bounds ?? null);
setDetails(bundle);
setGemeenteName(crop.metadata.gemeente ?? selectedMunicipality);
if (pendingSelectRef.current) {
const again = charges.find((f) => f.properties.locationId === pendingSelectRef.current);
pendingSelectRef.current = null;
if (again) setSelected(again);
}
}
};
load()
.catch((e) => console.error("data load failed", e))
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [selectedMunicipality]);
// Counts shown in the filter panel: same power/kind filtering as the map layers,
// so "the counts reflect the current view" actually holds.
const { passengerCount, freightCount } = useMemo(() => {
let p = 0;
let f = 0;
for (const feat of chargeFeatures) {
if (feat.properties.maxPowerKw < filters.minPowerKw) continue;
if (feat.properties.layer === "freight") {
if (filters.dedicatedFreightOnly && feat.properties.freightKind === "hpc") continue;
f++;
} else p++;
}
return { passengerCount: p, freightCount: f };
}, [chargeFeatures, filters.minPowerKw, filters.dedicatedFreightOnly]);
const selectedDetail = selected ? details[selected.properties.locationId] ?? null : null;
// From the national view, jump into the gemeente containing the selected point
// (found via the choropleth polygons) and re-open its detail panel there.
const jumpToGemeente = useMemo(() => {
if (!selected || selectedDetail || !isNational) return undefined;
const [lng, lat] = selected.geometry.coordinates;
const slug = findGemeenteSlug(choropleth, lng, lat);
if (!slug) return undefined;
const locationId = selected.properties.locationId;
return () => {
pendingSelectRef.current = locationId;
setAnalysisMetric(null);
setSelectedMunicipality(slug);
};
}, [selected, selectedDetail, isNational, choropleth]);
const handleAddressSelected = (slug: string) => {
setSelectedMunicipality(slug);
setMobileSidebarOpen(false);
};
return (
<div className="h-screen flex flex-col">
{/* Header */}
<header className="bg-white shadow-sm z-20">
<div className="px-3 py-2 md:px-4 md:py-3 flex items-center gap-2 md:gap-4">
<h1 className="text-lg md:text-xl font-bold text-gray-900 flex-shrink-0">
🔌 <span className="hidden sm:inline">Laadpalenviewer</span>
</h1>
<div className="flex-1 min-w-0 max-w-[200px] sm:max-w-xs md:max-w-md" data-tour="municipality">
<MunicipalitySelector
municipalities={municipalities}
selected={selectedMunicipality}
onChange={(slug) => {
setSelectedMunicipality(slug);
setMobileSidebarOpen(false);
}}
/>
</div>
<div className="hidden md:block flex-1 max-w-md">
<AddressSearchInput municipalities={municipalities} onAddressSelected={handleAddressSelected} />
</div>
{loading && (
<div className="flex items-center gap-2 text-xs md:text-sm text-gray-500">
<svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
<span className="hidden sm:inline">Laden…</span>
</div>
)}
<div className="hidden lg:flex gap-2 ml-auto">
<button
onClick={() => setShowTutorial(true)}
className="px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition"
>
Uitleg
</button>
<button
onClick={() => setShowShare(true)}
className="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
>
Delen
</button>
<button
onClick={() => setShowAbout(true)}
className="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
>
Over
</button>
</div>
</div>
</header>
{/* Main */}
<div className="flex-1 flex overflow-hidden relative">
{mobileSidebarOpen && (
<div className="md:hidden fixed inset-0 bg-black/50 z-30" onClick={() => setMobileSidebarOpen(false)} />
)}
<aside
className={`fixed md:relative inset-y-0 left-0 z-40 md:z-auto w-[85vw] max-w-[320px] md:w-80
bg-gray-50 p-3 md:p-4 overflow-y-auto space-y-3 md:space-y-4
transform transition-transform duration-300 ease-in-out
${mobileSidebarOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"} shadow-xl md:shadow-none`}
>
<StatsPanel gemeente={gemeenteName} chargeFeatures={chargeFeatures} />
{isNational && choropleth && (
<LayerSwitcher
metrics={choropleth.metadata.metrics}
active={analysisMetric}
onChange={(k) => {
setAnalysisMetric(k);
setSelectedArea(null);
}}
/>
)}
<FilterPanel
filters={filters}
onChange={setFilters}
passengerCount={passengerCount}
freightCount={freightCount}
/>
{isNational && (
<p className="text-xs text-gray-500 px-1">
Landelijk overzicht: alle laadpunten worden getoond zonder details. Kies een gemeente om
details (laadpunten, connectoren, tarieven) te laden.
</p>
)}
</aside>
<main className="flex-1 relative">
<MapDeck
chargeFeatures={chargeFeatures}
boundaryFeatures={boundaryFeatures}
bounds={bounds}
filters={choroActive ? { ...filters, showPassenger: false, showFreight: false } : filters}
selectedLocationId={selected?.properties.locationId ?? null}
onSelect={setSelected}
choropleth={choroActive ? choropleth : null}
analysisMetric={choroActive ? analysisMetric : null}
metricMeta={metricMeta}
onAreaSelect={(p) => setSelectedArea(p as AreaProps)}
/>
{choroActive && selectedArea && (
<GemeenteScorecard
area={selectedArea}
onClose={() => setSelectedArea(null)}
onOpenGemeente={(slug) => {
setSelectedArea(null);
setAnalysisMetric(null);
setSelectedMunicipality(slug);
}}
/>
)}
<LocationDetailPanel
selected={selected}
detail={selectedDetail}
loading={loading}
slug={selectedMunicipality}
onClose={() => setSelected(null)}
onJumpToGemeente={jumpToGemeente}
/>
{/* Mobile filter button */}
<button
onClick={() => setMobileSidebarOpen(true)}
className="md:hidden fixed bottom-6 left-4 z-20 bg-blue-600 text-white px-4 py-3 rounded-full shadow-lg hover:bg-blue-700 transition text-sm font-medium"
>
Filters & stats
</button>
</main>
</div>
{/* Footer */}
<footer className="bg-white border-t border-gray-200 px-3 md:px-4 py-2">
<div className="max-w-7xl mx-auto flex justify-between items-center text-xs text-gray-500">
<button onClick={() => setShowAbout(true)} className="text-blue-600 hover:underline">
Info over databronnen
</button>
<span>Bronnen: NDW OCPI · PDOK/CBS · Open Charge Map</span>
</div>
</footer>
<AboutModal
isOpen={showAbout}
onClose={() => setShowAbout(false)}
onStartTutorial={() => setShowTutorial(true)}
/>
<GuidedTour open={showTutorial} steps={tourSteps} onClose={() => setShowTutorial(false)} />
<ShareModal
isOpen={showShare}
onClose={() => setShowShare(false)}
municipality={selectedMunicipality}
municipalityName={municipalities.find((m) => m.slug === selectedMunicipality)?.name || selectedMunicipality}
/>
</div>
);
}
-153
View File
@@ -1,153 +0,0 @@
"use client";
import { X, PlayCircle } from "lucide-react";
interface Props {
isOpen: boolean;
onClose: () => void;
onStartTutorial?: () => void;
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section className="space-y-1">
<h3 className="font-semibold text-gray-900">{title}</h3>
<div className="text-gray-700 space-y-1">{children}</div>
</section>
);
}
export default function AboutModal({ isOpen, onClose, onStartTutorial }: Props) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
<div
className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[88vh] overflow-y-auto"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white z-10">
<h2 className="text-lg font-semibold">Over Laadpalenviewer — uitleg &amp; methodologie</h2>
<button onClick={onClose} className="p-1 hover:bg-gray-100 rounded">
<X className="h-5 w-5" />
</button>
</div>
<div className="p-4 space-y-4 text-sm">
{onStartTutorial && (
<button
onClick={() => {
onClose();
onStartTutorial();
}}
className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-blue-700 bg-blue-50 rounded-lg hover:bg-blue-100"
>
<PlayCircle className="h-4 w-4" /> Start de rondleiding
</button>
)}
<Section title="Wat toont deze app?">
<p>
Alle publiek toegankelijke laadpunten in Nederland in twee lagen — <strong>personenauto</strong> en
<strong> logistiek/vracht</strong> — plus een analyse-laag per gemeente (vraag, plaatsing, bezetting,
netimpact).
</p>
</Section>
<Section title="Databronnen">
<ul className="space-y-1">
<li>
<strong>NDW DOT-NL (OCPI 2.2.1)</strong> — laadlocaties, connectoren, tarieven en status.
Open data via opendata.ndw.nu.
</li>
<li>
<strong>NDW uurlijkse momentopname</strong> — wij downloaden de OCPI-export elk uur en leiden er
bezetting/status-historie uit af.
</li>
<li>
<strong>CBS Kerncijfers wijken en buurten (85984NED)</strong> — inwoners, huishoudens, inkomen,
stedelijkheid, autobezit. Licentie CC-BY 4.0 (© CBS).
</li>
<li>
<strong>PDOK CBS Gebiedsindelingen</strong> — gemeente- en provinciegrenzen. <strong>PDOK Locatieserver</strong> — adres zoeken.
</li>
<li>
<strong>Open Charge Map</strong> + handmatig samengestelde truck-hubs (Milence, WattHub) — extra
vrachtlocaties.
</li>
</ul>
</Section>
<Section title="Personenauto vs. logistiek/vracht">
<p>
Een laadpunt is <strong>dedicated truck</strong> bij een expliciet signaal: een truck-exploitant
(Milence/WattHub…), “truck” of “vrachtwagen” in de naam, de MCS/megawatt-standaard, of een logistiek
depot met ≥ 150 kW DC. Locaties die alléén op vermogen kwalificeren (DC ≥ 350 kW, zoals 400 kW-lanen
van personenauto-netwerken) heten <strong>truck-capable</strong> en krijgen een lichtere kleur — niet
elke locatie daarvan is fysiek toegankelijk voor een trekker-oplegger. Megawatt-locaties (≥ 1 MW of
MCS) krijgen een aparte kleur. Connectorvermogen wordt waar nodig afgeleid uit spanning × stroomsterkte.
</p>
</Section>
<Section title="Status &amp; gebruik">
<p>
Markerkleuren tonen de OCPI-status (beschikbaar/bezet/niet beschikbaar/onbekend) uit de laatste
uurlijkse snapshot. <strong>Bezetting</strong> = aandeel connectoren (EVSE&apos;s) met status “laden”. De
grafiek “Gebruik over de tijd” bouwt deze bezetting per uur op (24u/7d/30d/1j).
</p>
</Section>
<Section title="Berekeningen (analyse-laag)">
<ul className="space-y-1">
<li>
<strong>Verwachte vraag (peer-model)</strong> — een random-forest die het verwachte aantal
laadpunten voorspelt uit demografie (inwoners, huishoudens, auto&apos;s, inkomen, stedelijkheid,
adresdichtheid). Out-of-fold gevalideerd.
</li>
<li>
<strong>Tekort/overschot</strong> = werkelijk − verwacht. <strong>Plaatsingsprioriteit (0-100)</strong>{" "}
combineert relatief + absoluut tekort en bezetting.
</li>
<li>
<strong>Belasting nu (live)</strong> = (EVSE&apos;s die nú laden, uit de snapshot) × ~11 kW.
</li>
<li>
<strong>Potentiële piek (planning)</strong> = (alle EVSE&apos;s) × ~11 kW × 30% gelijktijdigheid.
</li>
<li>
<strong>Congestie-index</strong> = relatieve percentielrang van de piekbelasting per inwoner.
<strong> Netimpact-scenario</strong> herschaalt de piek met EV-groei en slim-laden.
</li>
</ul>
</Section>
<Section title="Belangrijke nuances / beperkingen">
<ul className="list-disc list-inside space-y-1 text-gray-600">
<li>
<strong>Vermogen wordt aangenomen</strong> (~11 kW/laadpunt): NDW publiceert <em>max_electric_power</em>
voor ±90% van de connectoren niet. Absolute kW zijn dus schattingen.
</li>
<li>
<strong>Congestie is gemodelleerd</strong> — er is geen DSO-capaciteit ingelezen (de Capaciteitskaart
is alleen een viewer). De index is relatief, geen knelpuntvoorspelling.
</li>
<li>
<strong>EV-aantallen</strong> zijn nog niet per gemeente meegenomen (RDW heeft geen locatie; CBS-EV per
regio volgt). Vraag is nu op autobezit/demografie gebaseerd.
</li>
<li>
Analyse is op <strong>gemeente-niveau</strong> (buurt/PC4 volgt). “Laadpunten” = OCPI-locaties; één
locatie kan meerdere sockets (EVSE&apos;s) hebben.
</li>
<li>NDW-dekking kan per gemeente verschillen (sommige CPO&apos;s ontbreken), wat aanbod kan onderschatten.</li>
</ul>
</Section>
<p className="text-xs text-gray-400 pt-2 border-t">
Attributie: data © CBS (CC-BY 4.0), PDOK (CC0), NDW (open data), Open Charge Map. Voor operationeel
gebruik altijd de bron raadplegen.
</p>
</div>
</div>
</div>
);
}
-388
View File
@@ -1,388 +0,0 @@
'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import { Municipality } from '@/types/charging';
// Mapping table for PDOK municipality names to our database names
// PDOK uses official CBS names, which differ from common/simplified names in our database
//
// Common issues with Dutch municipality names:
// 1. Apostrophe 's-: PDOK uses official 's-Gravenhage, 's-Hertogenbosch
// 2. Parenthetical disambiguation: PDOK omits periods: Bergen (NH) vs Bergen (NH.)
// 3. Regional identifiers: PDOK uses (O), (L), (NH), (ZH) for disambiguation
//
// PDOK returns: Our database has:
// - 's-Gravenhage -> Den Haag (common name)
// - 's-Hertogenbosch -> s-Hertogenbosch (no apostrophe)
// - Bergen (NH) -> Bergen (NH.) (with period)
// - Bergen (L) -> Bergen (L.) (with period)
// - Hengelo (O) -> Hengelo (simplified, no region identifier)
// - Beek (L) -> Beek (simplified, no region identifier)
// - Laren (NH) -> Laren (simplified, no region identifier)
// - Middelburg (Z) -> Middelburg (simplified, no region identifier)
// - Rijswijk (ZH) -> Rijswijk (simplified, no region identifier)
// - Stein (L) -> Stein (simplified, no region identifier)
const MUNICIPALITY_NAME_MAPPING: Record<string, string> = {
// Apostrophe 's- cases
"'s-gravenhage": "den haag",
"'s-hertogenbosch": "s-hertogenbosch",
// Bergen disambiguation (keep period)
"bergen (nh)": "bergen (nh.)",
"bergen (l)": "bergen (l.)",
// Regional identifiers removed in our database (without periods)
"hengelo (o)": "hengelo",
"beek (l)": "beek",
"laren (nh)": "laren",
"middelburg (z)": "middelburg",
"rijswijk (zh)": "rijswijk",
"stein (l)": "stein",
// With periods (just in case PDOK returns these variants)
"hengelo (o.)": "hengelo",
"beek (l.)": "beek",
"laren (nh.)": "laren",
"middelburg (z.)": "middelburg",
"rijswijk (zh.)": "rijswijk",
"stein (l.)": "stein",
};
interface SearchResult {
id: string;
displayName: string;
type: string;
municipality?: string;
score: number;
}
interface AddressDetails {
id: string;
displayName: string;
municipality: string;
street?: string;
houseNumber?: string;
postalCode?: string;
city?: string;
coordinates: {
latitude: number;
longitude: number;
} | null;
}
interface AddressSearchInputProps {
municipalities: Municipality[];
onAddressSelected: (
municipalitySlug: string,
coordinates: { latitude: number; longitude: number },
displayName: string
) => void;
}
export default function AddressSearchInput({
municipalities,
onAddressSelected,
}: AddressSearchInputProps) {
const [query, setQuery] = useState('');
const [results, setResults] = useState<SearchResult[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [showDropdown, setShowDropdown] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(-1);
const [error, setError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
// Debounced search function
const searchAddress = useCallback(async (searchQuery: string) => {
if (searchQuery.length < 3) {
setResults([]);
setShowDropdown(false);
return;
}
setIsLoading(true);
setError(null);
try {
const response = await fetch(
`/api/geocode?q=${encodeURIComponent(searchQuery)}`
);
if (!response.ok) {
throw new Error('Geocoding failed');
}
const data = await response.json();
setResults(data.results || []);
setShowDropdown(true);
setSelectedIndex(-1);
} catch (err) {
console.error('Geocoding error:', err);
setError('Adres zoeken mislukt. Probeer het opnieuw.');
setResults([]);
setShowDropdown(false);
} finally {
setIsLoading(false);
}
}, []);
// Handle input change with debouncing
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setQuery(value);
// Clear previous timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Set new timeout (300ms debounce)
timeoutRef.current = setTimeout(() => {
searchAddress(value);
}, 300);
};
// Handle result selection
const handleSelectResult = async (result: SearchResult) => {
setQuery(result.displayName);
setShowDropdown(false);
setIsLoading(true);
setError(null);
try {
// Lookup full details for the selected address
const response = await fetch(`/api/geocode?id=${encodeURIComponent(result.id)}`);
if (!response.ok) {
throw new Error('Address lookup failed');
}
const details: AddressDetails = await response.json();
if (!details.coordinates) {
setError('Geen coördinaten beschikbaar voor dit adres');
setIsLoading(false);
return;
}
if (!details.municipality) {
setError('Geen gemeente beschikbaar voor dit adres');
setIsLoading(false);
return;
}
// Find matching municipality in our data
// First normalize the PDOK municipality name
let normalizedMunicipality = details.municipality.toLowerCase();
// Check if we have a mapping for this PDOK name (e.g., 's-Gravenhage -> Den Haag)
if (MUNICIPALITY_NAME_MAPPING[normalizedMunicipality]) {
normalizedMunicipality = MUNICIPALITY_NAME_MAPPING[normalizedMunicipality];
}
// Try to find exact match
let municipality = municipalities.find(
(m) => m.name.toLowerCase() === normalizedMunicipality
);
// If no exact match, try to find by slug (some edge cases)
if (!municipality) {
const slugMatch = municipalities.find(
(m) => m.slug.toLowerCase() === normalizedMunicipality.replace(/\s+/g, '-').replace(/\./g, '')
);
if (slugMatch) {
municipality = slugMatch;
}
}
if (!municipality) {
setError(
`Gemeente "${details.municipality}" niet beschikbaar in de database`
);
setIsLoading(false);
return;
}
// Notify parent component
onAddressSelected(municipality.slug, details.coordinates, details.displayName);
} catch (err) {
console.error('Address lookup error:', err);
setError('Adres ophalen mislukt. Probeer het opnieuw.');
} finally {
setIsLoading(false);
}
};
// Handle keyboard navigation
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (!showDropdown || results.length === 0) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setSelectedIndex((prev) =>
prev < results.length - 1 ? prev + 1 : prev
);
break;
case 'ArrowUp':
e.preventDefault();
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : -1));
break;
case 'Enter':
e.preventDefault();
if (selectedIndex >= 0 && selectedIndex < results.length) {
handleSelectResult(results[selectedIndex]);
}
break;
case 'Escape':
setShowDropdown(false);
setSelectedIndex(-1);
break;
}
};
// Click outside to close dropdown
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node) &&
inputRef.current &&
!inputRef.current.contains(event.target as Node)
) {
setShowDropdown(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return (
<div className="relative">
<div className="relative">
<input
ref={inputRef}
type="text"
value={query}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder="Zoek adres..."
className="w-full px-3 md:px-4 py-2.5 md:py-2 pr-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 text-sm"
/>
{isLoading && (
<div className="absolute right-3 top-1/2 transform -translate-y-1/2">
<svg
className="animate-spin h-5 w-5 text-gray-400"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
</div>
)}
{!isLoading && query && (
<button
onClick={() => {
setQuery('');
setResults([]);
setShowDropdown(false);
setError(null);
inputRef.current?.focus();
}}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
)}
</div>
{/* Error message */}
{error && (
<div className="mt-2 text-sm text-red-600">{error}</div>
)}
{/* Dropdown results */}
{showDropdown && results.length > 0 && (
<div
ref={dropdownRef}
className="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-[50vh] md:max-h-96 overflow-y-auto"
>
{results.map((result, index) => (
<button
key={result.id}
onClick={() => handleSelectResult(result)}
className={`w-full px-3 md:px-4 py-3 text-left hover:bg-blue-50 active:bg-blue-100 transition ${
index === selectedIndex ? 'bg-blue-50' : ''
} ${index !== results.length - 1 ? 'border-b border-gray-200' : ''}`}
>
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 truncate">
{result.displayName}
</div>
{result.municipality && (
<div className="text-xs text-gray-500 mt-0.5 truncate">
{result.municipality}
</div>
)}
</div>
<div className="flex-shrink-0">
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
{result.type === 'adres' ? 'Adres' :
result.type === 'weg' ? 'Straat' :
result.type === 'postcode' ? 'PC' :
result.type === 'woonplaats' ? 'Plaats' : result.type}
</span>
</div>
</div>
</button>
))}
</div>
)}
{/* No results message */}
{showDropdown && !isLoading && query.length >= 3 && results.length === 0 && (
<div
ref={dropdownRef}
className="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg px-3 md:px-4 py-3"
>
<div className="text-sm text-gray-500">
Geen resultaten voor &quot;{query}&quot;
</div>
</div>
)}
</div>
);
}
-143
View File
@@ -1,143 +0,0 @@
"use client";
import type { Filters } from "@/types/charging";
import { LEGEND } from "@/lib/colors";
import InfoTip from "@/components/InfoTip";
interface FilterPanelProps {
filters: Filters;
onChange: (f: Filters) => void;
passengerCount: number;
freightCount: number;
}
const POWER_STEPS = [0, 50, 150, 350, 1000];
export default function FilterPanel({ filters, onChange, passengerCount, freightCount }: FilterPanelProps) {
const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch });
return (
<div className="bg-white rounded-lg shadow-sm p-4 space-y-4" data-tour="layers">
<h3 className="text-sm font-semibold text-gray-900 flex items-center gap-1">
Kaartlagen
<InfoTip title="Kaartlagen">
Zet de twee laadpunt-lagen (personenauto / vracht) en de gemeente-/provinciegrenzen aan of uit, en
filter op minimaal laadvermogen. De tellingen rechts tonen het aantal in de huidige weergave.
</InfoTip>
</h3>
{/* Layer toggles */}
<div className="space-y-2">
<label className="flex items-center justify-between gap-2 cursor-pointer">
<span className="flex items-center gap-2 text-sm text-gray-800">
<input
type="checkbox"
checked={filters.showPassenger}
onChange={(e) => set({ showPassenger: e.target.checked })}
className="w-4 h-4 accent-blue-600"
/>
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.available }} />
Personenauto
</span>
<span className="text-xs text-gray-500 tabular-nums">{passengerCount.toLocaleString("nl-NL")}</span>
</label>
<label className="flex items-center justify-between gap-2 cursor-pointer">
<span className="flex items-center gap-2 text-sm text-gray-800">
<input
type="checkbox"
checked={filters.showFreight}
onChange={(e) => set({ showFreight: e.target.checked })}
className="w-4 h-4 accent-amber-500"
/>
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.freight }} />
Logistiek / vracht
</span>
<span className="text-xs text-gray-500 tabular-nums">{freightCount.toLocaleString("nl-NL")}</span>
</label>
{filters.showFreight && (
<label className="flex items-center gap-2 cursor-pointer pl-6">
<input
type="checkbox"
checked={filters.dedicatedFreightOnly}
onChange={(e) => set({ dedicatedFreightOnly: e.target.checked })}
className="w-4 h-4 accent-amber-600"
/>
<span className="text-sm text-gray-800 flex items-center gap-1">
Alleen dedicated truck-locaties
<InfoTip title="Dedicated truck-locaties">
Verbergt snelladers die alleen op vermogen (≥350 kW DC) als truck-capable gelden, zoals
400 kW-lanen van personenauto-netwerken. Wat overblijft zijn locaties met een expliciet
trucksignaal: exploitant (Milence, WattHub…), “truck” in de naam, MCS of een logistiek depot.
</InfoTip>
</span>
</label>
)}
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={filters.showBoundary}
onChange={(e) => set({ showBoundary: e.target.checked })}
className="w-4 h-4 accent-indigo-600"
/>
<span className="w-3 h-3 rounded-sm border-2" style={{ borderColor: LEGEND.boundary }} />
<span className="text-sm text-gray-800">Gemeente-/provinciegrens</span>
</label>
</div>
{/* Power filter */}
<div className="pt-2 border-t border-gray-100">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium text-gray-700 flex items-center gap-1">
Min. vermogen
<InfoTip title="Minimaal vermogen">
Toon alleen laadpunten met een maximaal connectorvermogen ≥ de gekozen kW. Waar NDW geen
vermogen publiceert wordt het afgeleid uit spanning × stroomsterkte; een klein restdeel blijft
onbekend (0 kW) en verdwijnt bij een hoge drempel.
</InfoTip>
</span>
<span className="text-xs text-gray-500">
{filters.minPowerKw === 0 ? "alle" : `≥ ${filters.minPowerKw} kW`}
</span>
</div>
<div className="flex gap-1">
{POWER_STEPS.map((kw) => (
<button
key={kw}
onClick={() => set({ minPowerKw: kw })}
className={`flex-1 px-1 py-1.5 text-xs rounded transition ${
filters.minPowerKw === kw
? "bg-blue-600 text-white"
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
}`}
>
{kw === 0 ? "Alle" : kw}
</button>
))}
</div>
</div>
{/* Price coloring */}
<div className="pt-2 border-t border-gray-100">
<label className="flex items-center justify-between gap-2 cursor-pointer">
<span className="flex items-center gap-2 text-sm text-gray-800">
<input
type="checkbox"
checked={filters.colorByPrice}
onChange={(e) => set({ colorByPrice: e.target.checked })}
className="w-4 h-4 accent-rose-600"
/>
Kleur op prijs (€/kWh)
</span>
<InfoTip title="Kleur op prijs">
Kleurt de laadpunten naar het actuele energietarief (€/kWh) uit de OCPI-tarieven van NDW — lichter
is goedkoper, donkerder duurder. Punten zonder gepubliceerd tarief blijven grijs (NDW heeft voor
±50% geen prijs). De prijs is een momentopname uit de laatste data-update.
</InfoTip>
</label>
</div>
</div>
);
}
-212
View File
@@ -1,212 +0,0 @@
"use client";
import { useState } from "react";
import { X, ArrowRight } from "lucide-react";
import type { AreaProps } from "@/types/analysis";
import InfoTip from "@/components/InfoTip";
interface Props {
area: AreaProps | null;
onClose: () => void;
onOpenGemeente?: (slug: string) => void;
}
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
const fmt = (v: number | null, d = 0) =>
v === null ? "–" : v.toLocaleString("nl-NL", { minimumFractionDigits: d, maximumFractionDigits: d });
function Bar({ pct, color }: { pct: number | null; color: string }) {
return (
<div className="h-1.5 bg-gray-100 rounded overflow-hidden">
<div className="h-full rounded" style={{ width: `${pct ?? 0}%`, background: color }} />
</div>
);
}
function Row({ label, value, pct, color = "#3b82f6" }: { label: string; value: string; pct?: number | null; color?: string }) {
return (
<div className="space-y-0.5">
<div className="flex justify-between text-sm">
<span className="text-gray-600">{label}</span>
<span className="font-medium text-gray-900">{value}</span>
</div>
{pct !== undefined && <Bar pct={pct} color={color} />}
</div>
);
}
export default function GemeenteScorecard({ area, onClose, onOpenGemeente }: Props) {
const [growth, setGrowth] = useState(50); // % EV growth
const [smart, setSmart] = useState(20); // % peak reduction via smart charging
if (!area) return null;
const basePeak = num(area.est_peak_load_kw) ?? 0; // = potential peak (planning)
const projected = basePeak * (1 + growth / 100) * (1 - smart / 100);
const inw = num(area.inwoners) ?? 0;
const projPer1000 = inw ? (projected / inw) * 1000 : null;
const livePeak = num(area.live_peak_load_kw);
const occNow = num(area.occupancy_now);
const evse = num(area.evse_total);
const chargingNow = num(area.charging_now);
const gap = num(area.supply_gap);
const slug = typeof area.slug === "string" ? area.slug : null;
return (
<div
data-tour="scorecard"
className="absolute top-4 right-14 w-96 max-w-[calc(100vw-5rem)] max-h-[calc(100%-2rem)] bg-white rounded-lg shadow-lg overflow-hidden flex flex-col z-10"
>
<div className="p-4 border-b bg-gray-50 flex justify-between items-start">
<div>
<h3 className="font-semibold text-lg">{area.gemeente}</h3>
<p className="text-xs text-gray-500">Gemeente-scorecard (laadinfra)</p>
</div>
<button onClick={onClose} className="p-1 hover:bg-gray-200 rounded">
<X className="h-5 w-5" />
</button>
</div>
<div className="overflow-y-auto flex-1 p-4 space-y-4">
{/* Aanbod */}
<section className="space-y-2">
<h4 className="text-sm font-medium text-gray-700">Aanbod</h4>
<Row label="Laadlocaties (personen)" value={fmt(num(area.chargers_passenger))} />
<Row label="Vracht-laadpunten" value={fmt(num(area.chargers_freight))} />
{evse !== null && <Row label="Laadpunten (sockets/EVSEs)" value={fmt(evse)} />}
<Row label="Per 1.000 inwoners" value={fmt(num(area.chargers_per_1000_inw), 1)} pct={num(area.supply_pct)} color="#22c55e" />
<Row label="Gem. bezetting" value={num(area.avg_occupancy) === null ? "–" : `${fmt(num(area.avg_occupancy), 1)}%`} pct={num(area.occupancy_pct)} color="#3b82f6" />
</section>
{/* Prijs */}
{num(area.price_kwh_median) !== null && (
<section className="space-y-2 pt-2 border-t border-gray-100">
<h4 className="text-sm font-medium text-gray-700 flex items-center gap-1">
Tarief (€/kWh)
<InfoTip title="Tarief (€/kWh)">
Mediaan van het actuele energietarief uit de OCPI-tarieven (NDW), over laadlocaties met een
gepubliceerde prijs. De balk toont de relatieve percentielrang (hoger = duurder dan andere
gemeenten). ±50% van de connectoren publiceert géén tarief; dit is een momentopname uit de
laatste data-update.
</InfoTip>
</h4>
<Row
label="Mediaan tarief"
value={`€ ${fmt(num(area.price_kwh_median), 3)}`}
pct={num(area.price_pct)}
color="#f43f5e"
/>
{num(area.price_kwh_mean) !== null && (
<Row label="Gemiddeld tarief" value={`€ ${fmt(num(area.price_kwh_mean), 3)}`} />
)}
<p className="text-[10px] text-gray-400">
Op basis van {fmt(num(area.price_kwh_n))} laadlocaties met gepubliceerd tarief.
</p>
</section>
)}
{/* Live load now */}
{livePeak !== null && (
<section className="space-y-1 pt-2 border-t border-gray-100">
<h4 className="text-sm font-medium text-gray-700 flex items-center gap-1">
Belasting nu (live)
<InfoTip title="Belasting nu (live)">
= aantal laadpunten dat op dit moment laadt (uit de uurlijkse OCPI-snapshot) × ~11 kW per
laadpunt. Het vermogen is aangenomen omdat NDW het voor ±90% van de connectoren niet publiceert.
Dit is een live momentopname, geen gemeten kW.
</InfoTip>
</h4>
<div className="bg-green-50 rounded p-2">
<div className="flex justify-between text-sm">
<span className="text-green-900">Geschatte belasting nu</span>
<span className="font-semibold text-green-900">{fmt(livePeak)} kW</span>
</div>
<div className="text-xs text-green-700">
{chargingNow !== null ? `${fmt(chargingNow)} laadpunten aan het laden` : ""}
{occNow !== null ? ` · ${fmt(occNow, 1)}% bezet nu` : ""}
</div>
</div>
<p className="text-[10px] text-gray-400">
Live uit OCPI-status (uurlijkse snapshot) × {`~11 kW per laadpunt`} — vermogen aangenomen,
want NDW publiceert het voor ±90% van de connectoren niet.
</p>
</section>
)}
{/* Vraag & plaatsing */}
<section className="space-y-2 pt-2 border-t border-gray-100">
<h4 className="text-sm font-medium text-gray-700 flex items-center gap-1">
Vraag &amp; plaatsing
<InfoTip title="Vraag & plaatsing (peer-model)">
Een random-forest voorspelt het “verwachte” aantal laadpunten uit demografie (inwoners,
huishoudens, auto&apos;s, inkomen, stedelijkheid, adresdichtheid). Werkelijk − verwacht =
tekort/overschot; de plaatsingsprioriteit (0-100) weegt relatief + absoluut tekort en bezetting.
</InfoTip>
</h4>
<Row label="Verwacht (peer-model)" value={fmt(num(area.expected_chargers))} />
<Row
label="Tekort / overschot"
value={gap === null ? "–" : `${gap > 0 ? "+" : ""}${fmt(gap)}`}
/>
<div className={`text-xs rounded px-2 py-1 ${gap !== null && gap < 0 ? "bg-amber-50 text-amber-800" : "bg-green-50 text-green-800"}`}>
{gap !== null && gap < 0
? `Ondergemiddeld aanbod t.o.v. vergelijkbare gemeenten — plaatsingsprioriteit ${fmt(num(area.siting_priority))}/100.`
: "Aanbod op of boven verwachting voor vergelijkbare gemeenten."}
</div>
</section>
{/* Netimpact scenario */}
<section className="space-y-2 pt-2 border-t border-gray-100">
<h4 className="text-sm font-medium text-gray-700 flex items-center gap-1">
Netimpact (scenario)
<InfoTip title="Netimpact-scenario">
Potentiële piek = alle laadpunten (EVSE&apos;s) × ~11 kW × 30% gelijktijdigheid. De schuiven
herschalen dit met EV-groei (meer laden) en slim laden (piekreductie):
piek × (1+groei) × (1−reductie). Gemodelleerd — er is geen netcapaciteit (DSO) ingelezen.
</InfoTip>
</h4>
<Row label="Potentiële piek (planning)" value={`${fmt(basePeak)} kW`} />
<div>
<div className="flex justify-between text-xs text-gray-600">
<span>EV-groei</span>
<span>+{growth}%</span>
</div>
<input type="range" min={0} max={200} value={growth} onChange={(e) => setGrowth(+e.target.value)} className="w-full accent-blue-600" />
</div>
<div>
<div className="flex justify-between text-xs text-gray-600">
<span>Slim laden (piekreductie)</span>
<span>−{smart}%</span>
</div>
<input type="range" min={0} max={50} value={smart} onChange={(e) => setSmart(+e.target.value)} className="w-full accent-green-600" />
</div>
<div className="bg-blue-50 rounded p-2 text-sm">
<div className="flex justify-between">
<span className="text-blue-900">Projectie piekbelasting</span>
<span className="font-semibold text-blue-900">{fmt(projected)} kW</span>
</div>
{projPer1000 !== null && (
<div className="flex justify-between text-xs text-blue-700">
<span>per 1.000 inwoners</span>
<span>{fmt(projPer1000, 1)} kW</span>
</div>
)}
</div>
<p className="text-[10px] text-gray-400">
Potentiële piek = alle laadpunten × ~11 kW × 30% gelijktijdigheid. Gemodelleerd
(geen DSO-capaciteit ingelezen); congestie-index is relatief.
</p>
</section>
{slug && onOpenGemeente && (
<button
onClick={() => onOpenGemeente(slug)}
className="w-full flex items-center justify-center gap-1 px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
>
Open {area.gemeente} op de kaart <ArrowRight className="h-4 w-4" />
</button>
)}
</div>
</div>
);
}
-199
View File
@@ -1,199 +0,0 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import { X, ChevronLeft, ChevronRight } from "lucide-react";
export interface TourStep {
title: string;
body: React.ReactNode;
target?: string; // data-tour selector to spotlight; omit for centered
action?: () => void; // drives app state on entering the step
pad?: number; // spotlight padding
}
interface Props {
open: boolean;
steps: TourStep[];
onClose: () => void;
}
type Rect = { top: number; left: number; width: number; height: number };
const PAD = 8;
export default function GuidedTour({ open, steps, onClose }: Props) {
const [idx, setIdx] = useState(0);
const [rect, setRect] = useState<Rect | null>(null);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const step = steps[idx];
// Find + measure the target element (polling, since app state/data loads async).
const locate = useCallback((selector?: string) => {
if (pollRef.current) clearInterval(pollRef.current);
if (!selector) {
setRect(null);
return;
}
let tries = 0;
const tick = () => {
const el = document.querySelector(selector) as HTMLElement | null;
if (el) {
const r = el.getBoundingClientRect();
if (r.width > 0 && r.height > 0) {
setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
if (pollRef.current) clearInterval(pollRef.current);
return;
}
}
if (++tries > 24) {
setRect(null);
if (pollRef.current) clearInterval(pollRef.current);
}
};
tick();
pollRef.current = setInterval(tick, 150);
}, []);
// On entering a step: run its action, then locate the target.
useEffect(() => {
if (!open) return;
step?.action?.();
const t = setTimeout(() => locate(step?.target), 350);
return () => clearTimeout(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, idx]);
// Keep the spotlight aligned on resize/scroll.
useEffect(() => {
if (!open) return;
const on = () => step?.target && locate(step.target);
window.addEventListener("resize", on);
window.addEventListener("scroll", on, true);
return () => {
window.removeEventListener("resize", on);
window.removeEventListener("scroll", on, true);
};
}, [open, step, locate]);
useEffect(() => {
if (!open) setIdx(0);
}, [open]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!open) return;
if (e.key === "Escape") onClose();
if (e.key === "ArrowRight") setIdx((v) => Math.min(steps.length - 1, v + 1));
if (e.key === "ArrowLeft") setIdx((v) => Math.max(0, v - 1));
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, steps.length, onClose]);
if (!open) return null;
const last = idx === steps.length - 1;
const pad = step?.pad ?? PAD;
// Spotlight hole geometry.
const hole = rect
? {
top: Math.max(0, rect.top - pad),
left: Math.max(0, rect.left - pad),
width: rect.width + pad * 2,
height: rect.height + pad * 2,
}
: null;
// Place the card near the hole (or centered).
const vw = typeof window !== "undefined" ? window.innerWidth : 1280;
const vh = typeof window !== "undefined" ? window.innerHeight : 800;
const CARD_W = 340;
let cardStyle: React.CSSProperties = {
left: vw / 2 - CARD_W / 2,
top: vh / 2 - 120,
};
if (hole) {
const spaceRight = vw - (hole.left + hole.width);
const spaceLeft = hole.left;
let left: number;
let top = Math.min(Math.max(12, hole.top), vh - 240);
if (spaceRight > CARD_W + 24) left = hole.left + hole.width + 16;
else if (spaceLeft > CARD_W + 24) left = hole.left - CARD_W - 16;
else {
// place below or above, centered horizontally over the hole
left = Math.min(Math.max(12, hole.left + hole.width / 2 - CARD_W / 2), vw - CARD_W - 12);
top = hole.top + hole.height + 16 < vh - 220 ? hole.top + hole.height + 16 : Math.max(12, hole.top - 230);
}
cardStyle = { left, top };
}
// Four blurred panes around the hole (everything except the target is dimmed+blurred).
const Pane = ({ s }: { s: React.CSSProperties }) => (
<div className="fixed bg-slate-900/55 backdrop-blur-[3px] z-[140]" style={s} />
);
return (
<>
{hole ? (
<>
<Pane s={{ top: 0, left: 0, width: vw, height: hole.top }} />
<Pane s={{ top: hole.top + hole.height, left: 0, width: vw, height: vh - (hole.top + hole.height) }} />
<Pane s={{ top: hole.top, left: 0, width: hole.left, height: hole.height }} />
<Pane s={{ top: hole.top, left: hole.left + hole.width, width: vw - (hole.left + hole.width), height: hole.height }} />
<div
className="fixed z-[142] rounded-lg ring-2 ring-blue-500 pointer-events-none"
style={{ top: hole.top, left: hole.left, width: hole.width, height: hole.height }}
/>
</>
) : (
<div className="fixed inset-0 bg-slate-900/55 backdrop-blur-[3px] z-[140]" />
)}
{/* Card */}
<div
className="fixed z-[150] bg-white rounded-xl shadow-2xl w-[340px] max-w-[calc(100vw-24px)]"
style={cardStyle}
>
<div className="flex items-center justify-between px-4 py-2.5 border-b">
<span className="text-xs font-medium text-gray-400">
Rondleiding · {idx + 1}/{steps.length}
</span>
<button onClick={onClose} className="p-1 hover:bg-gray-100 rounded" aria-label="Sluiten">
<X className="h-4 w-4" />
</button>
</div>
<div className="p-4">
<h2 className="text-base font-semibold mb-1.5">{step.title}</h2>
<div className="text-sm text-gray-700 space-y-2">{step.body}</div>
</div>
<div className="flex items-center justify-between px-4 py-2.5 border-t bg-gray-50">
<button
onClick={() => setIdx((v) => Math.max(0, v - 1))}
disabled={idx === 0}
className="flex items-center gap-1 px-2.5 py-1.5 text-sm rounded-lg disabled:opacity-40 hover:bg-gray-200"
>
<ChevronLeft className="h-4 w-4" /> Vorige
</button>
<div className="flex gap-1">
{steps.map((_, i) => (
<span key={i} className={`w-1.5 h-1.5 rounded-full ${i === idx ? "bg-blue-600" : "bg-gray-300"}`} />
))}
</div>
{last ? (
<button onClick={onClose} className="px-3 py-1.5 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700">
Klaar
</button>
) : (
<button
onClick={() => setIdx((v) => Math.min(steps.length - 1, v + 1))}
className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
>
Volgende <ChevronRight className="h-4 w-4" />
</button>
)}
</div>
</div>
</>
);
}
-90
View File
@@ -1,90 +0,0 @@
"use client";
import { useState, useRef, useLayoutEffect, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { Info } from "lucide-react";
interface Props {
title?: string;
children: React.ReactNode;
className?: string;
}
// Small "?" info icon that shows a portal popover (so it never clips inside
// scrollable panels). Opens on hover and on click (touch-friendly).
export default function InfoTip({ title, children, className }: Props) {
const [open, setOpen] = useState(false);
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
const btnRef = useRef<HTMLButtonElement>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const WIDTH = 270;
const place = useCallback(() => {
const r = btnRef.current?.getBoundingClientRect();
if (!r) return;
let left = r.left + r.width / 2 - WIDTH / 2;
left = Math.max(8, Math.min(left, window.innerWidth - WIDTH - 8));
setPos({ top: r.bottom + 6, left });
}, []);
useLayoutEffect(() => {
if (open) place();
}, [open, place]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
const onScroll = () => setOpen(false);
window.addEventListener("keydown", onKey);
window.addEventListener("scroll", onScroll, true);
window.addEventListener("resize", onScroll);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("scroll", onScroll, true);
window.removeEventListener("resize", onScroll);
};
}, [open]);
const show = () => {
if (closeTimer.current) clearTimeout(closeTimer.current);
setOpen(true);
};
const hide = () => {
if (closeTimer.current) clearTimeout(closeTimer.current);
closeTimer.current = setTimeout(() => setOpen(false), 120);
};
return (
<>
<button
ref={btnRef}
type="button"
aria-label={title || "Uitleg"}
onClick={(e) => {
e.stopPropagation();
setOpen((o) => !o);
}}
onMouseEnter={show}
onMouseLeave={hide}
className={`inline-flex items-center justify-center align-middle text-gray-400 hover:text-blue-600 ${className ?? ""}`}
>
<Info className="w-3.5 h-3.5" />
</button>
{open &&
pos &&
createPortal(
<div
style={{ position: "fixed", top: pos.top, left: pos.left, width: WIDTH }}
className="z-[200] bg-gray-900 text-white text-xs rounded-lg shadow-xl p-3 leading-relaxed"
onMouseEnter={show}
onMouseLeave={hide}
>
{title && <div className="font-semibold mb-1">{title}</div>}
<div className="text-gray-200 space-y-1">{children}</div>
</div>,
document.body,
)}
</>
);
}
-58
View File
@@ -1,58 +0,0 @@
"use client";
import { useMemo } from "react";
import type { MetricMeta } from "@/types/analysis";
import InfoTip from "@/components/InfoTip";
interface Props {
metrics: MetricMeta[];
active: string | null;
onChange: (key: string | null) => void;
}
export default function LayerSwitcher({ metrics, active, onChange }: Props) {
const groups = useMemo(() => {
const m = new Map<string, MetricMeta[]>();
for (const metric of metrics) {
const cat = metric.category ?? "Overig";
if (!m.has(cat)) m.set(cat, []);
m.get(cat)!.push(metric);
}
return [...m.entries()];
}, [metrics]);
const activeMeta = metrics.find((m) => m.key === active);
return (
<div className="bg-white rounded-lg shadow-sm p-4 space-y-2" data-tour="analyse">
<h3 className="text-sm font-semibold text-gray-900 flex items-center gap-1">
Analyse (per gemeente)
<InfoTip title="Analyse-laag">
Toont een indicator als kleurvlak (choropleth) over alle gemeenten. Donker = hoge waarde. Klik een
gemeente voor de scorecard met onderliggende cijfers en berekeningen. Alleen beschikbaar in de
“Nederland (totaal)”-weergave.
</InfoTip>
</h3>
<p className="text-xs text-gray-500">Kies een indicator. Klik een gemeente voor de scorecard.</p>
<select
value={active ?? ""}
onChange={(e) => onChange(e.target.value || null)}
className="w-full text-sm border border-gray-300 rounded-lg px-2 py-2 bg-white"
>
<option value="">Geen (laadpunten tonen)</option>
{groups.map(([cat, items]) => (
<optgroup key={cat} label={cat}>
{items.map((m) => (
<option key={m.key} value={m.key}>
{m.label}
</option>
))}
</optgroup>
))}
</select>
{activeMeta?.desc && (
<p className="text-xs text-gray-600 bg-gray-50 rounded p-2 leading-relaxed">{activeMeta.desc}</p>
)}
</div>
);
}
-246
View File
@@ -1,246 +0,0 @@
"use client";
import { X, ExternalLink, Clock, Zap, MapPin, Building2, Truck } from "lucide-react";
import type { ChargeFeature, EnrichedConnector, EnrichedLocation } from "@/types/charging";
import { formatConnectorStandard, formatPowerType, statusColorClass, statusLabel } from "@/lib/connectorLabels";
import UsageChart from "@/components/UsageChart";
const fmtPrice = (v: number) =>
v.toLocaleString("nl-NL", { style: "currency", currency: "EUR", minimumFractionDigits: 2, maximumFractionDigits: 3 });
// Prefer the price baked by the pipeline; fall back to a best-effort parse of the
// raw tariff (for data generated before the price field existed).
// Best-effort connector kW mirroring the pipeline: plausible declared power,
// else derived from V×A (×3 for three-phase AC). Filters out garbage values
// like 7,360,000 W on a 230 V/32 A AC post.
function connectorKw(c: EnrichedConnector): number | null {
const declared = c.max_electric_power ?? 0;
if (declared > 0 && declared <= 1_500_000) return declared / 1000;
const v = c.max_voltage ?? 0;
const a = c.max_amperage ?? 0;
if (v <= 0 || a <= 0) return null;
const phases = (c.power_type ?? "").toUpperCase() === "AC_3_PHASE" ? 3 : 1;
return (v * a * phases) / 1000;
}
const FREIGHT_REASON_LABEL: Record<string, string> = {
operator: "truck-exploitant",
"truck-name": "“truck” in de naam",
mcs: "MCS-aansluiting",
"depot-name": "logistiek depot",
motorway: "snelweglocatie ≥350 kW",
power: "alleen op vermogen (≥350 kW DC)",
curated: "handmatig toegevoegde hub",
};
function connectorPriceKwh(c: EnrichedConnector): number | null {
if (typeof c.priceKwh === "number") return c.priceKwh;
for (const t of c.tariffs ?? []) {
for (const el of t.elements ?? []) {
const energy = el.price_components?.find((pc) => pc.type === "ENERGY");
if (energy && typeof energy.price === "number") return energy.price;
}
}
return null;
}
interface Props {
selected: ChargeFeature | null;
detail: EnrichedLocation | null;
loading: boolean;
slug?: string; // gemeente slug for usage history (undefined / 'nederland' = no chart)
onClose: () => void;
onJumpToGemeente?: () => void;
}
export default function LocationDetailPanel({ selected, detail, loading, slug, onClose, onJumpToGemeente }: Props) {
if (!selected) return null;
const p = selected.properties;
const isFreight = p.layer === "freight";
return (
<div
data-tour="detail"
className="absolute top-4 right-14 w-96 max-w-[calc(100vw-5rem)] max-h-[calc(100%-2rem)] bg-white rounded-lg shadow-lg overflow-hidden flex flex-col z-10"
>
<div className="p-4 border-b bg-gray-50 flex-shrink-0">
<div className="flex justify-between items-start">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span
className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs text-white ${
isFreight ? "bg-amber-500" : "bg-blue-500"
}`}
>
{isFreight ? <Truck className="h-3 w-3" /> : <Zap className="h-3 w-3" />}
{isFreight ? (p.freightKind === "hpc" ? "Truck-capable" : "Truck") : "Personenauto"}
</span>
{p.isMegawatt && (
<span className="px-1.5 py-0.5 rounded text-xs text-white bg-orange-600">Megawatt</span>
)}
</div>
{isFreight && p.freightReason && FREIGHT_REASON_LABEL[p.freightReason] && (
<div className="text-xs text-amber-700 mt-1">
Classificatie: {FREIGHT_REASON_LABEL[p.freightReason]}
</div>
)}
<h3 className="font-semibold text-lg truncate mt-1">{p.name}</h3>
{p.address && (
<div className="flex items-center gap-1 text-sm text-gray-600 mt-1">
<MapPin className="h-3 w-3 flex-shrink-0" />
<span className="truncate">
{p.address}
{p.city ? `, ${p.city}` : ""}
</span>
</div>
)}
</div>
<button onClick={onClose} className="p-1 hover:bg-gray-200 rounded ml-2 flex-shrink-0">
<X className="h-5 w-5" />
</button>
</div>
</div>
<div className="overflow-y-auto flex-1 p-4 space-y-4">
{/* Operator */}
<div className="space-y-2">
<h4 className="font-medium text-sm text-gray-700 flex items-center gap-2">
<Building2 className="h-4 w-4" />
Exploitant
</h4>
<div className="bg-gray-50 rounded p-3 text-sm">
<div className="font-medium">{p.operatorName || "Onbekend"}</div>
{detail?.operatorWebsite && (
<a
href={detail.operatorWebsite}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline flex items-center gap-1 text-xs mt-1"
>
{detail.operatorWebsite}
<ExternalLink className="h-3 w-3" />
</a>
)}
<div className="text-xs text-gray-500 mt-1">Bron: {p.source.toUpperCase()}</div>
</div>
</div>
{/* Usage over time (gemeente view only; per-gemeente snapshot history) */}
{slug && slug !== "nederland" && <UsageChart slug={slug} locationId={p.locationId} />}
{loading && (
<div className="text-sm text-gray-500 italic flex items-center gap-2">
<span className="animate-spin h-4 w-4 border-2 border-gray-300 border-t-gray-600 rounded-full" />
Details laden…
</div>
)}
{!loading && detail && (
<>
{/* General */}
<div className="space-y-2">
<h4 className="font-medium text-sm text-gray-700 flex items-center gap-2">
<Clock className="h-4 w-4" />
Gegevens
</h4>
<div className="bg-gray-50 rounded p-3 text-sm space-y-1">
<Row label="24/7 toegang">
<span className={detail.twentyFourSeven ? "text-green-600" : "text-gray-500"}>
{detail.twentyFourSeven ? "Ja" : "Nee"}
</span>
</Row>
{detail.maxPowerKw > 0 && <Row label="Max. vermogen">{detail.maxPowerKw} kW</Row>}
{detail.parkingType && (
<Row label="Parkeren">{detail.parkingType.replace(/_/g, " ")}</Row>
)}
<Row label="OCPI ID">
<span className="font-mono text-xs">{detail.ocpiId}</span>
</Row>
<Row label="Bijgewerkt">
<span className="text-xs">{new Date(detail.lastUpdated).toLocaleString("nl-NL")}</span>
</Row>
</div>
</div>
{/* EVSEs */}
{detail.evses.length > 0 && (
<div className="space-y-2">
<h4 className="font-medium text-sm text-gray-700 flex items-center gap-2">
<Zap className="h-4 w-4" />
Laadpunten ({detail.evses.length})
</h4>
<div className="space-y-3">
{detail.evses.map((evse) => (
<div key={evse.uid} className="bg-gray-50 rounded p-3 text-sm">
<div className="flex items-center justify-between mb-2">
<span className="font-mono text-xs">{evse.evse_id}</span>
<span className={`px-2 py-0.5 rounded text-xs text-white ${statusColorClass(evse.status)}`}>
{statusLabel(evse.status)}
</span>
</div>
{evse.connectors.length > 0 && (
<div className="mt-1 pt-2 border-t border-gray-200 space-y-2">
{evse.connectors.map((c) => (
<div key={c.id} className="text-xs space-y-1">
<div className="flex justify-between">
<span className="font-medium">{formatConnectorStandard(c.standard)}</span>
<span className="text-gray-500">{c.format}</span>
</div>
<div className="flex justify-between text-gray-600">
<span>{formatPowerType(c.power_type)}</span>
{(() => {
const kw = connectorKw(c);
return kw ? <span className="font-medium">{kw.toFixed(1)} kW</span> : null;
})()}
</div>
{(() => {
const price = connectorPriceKwh(c);
if (price === null) return null;
return (
<div className="text-gray-500">
Tarief: <span className="font-medium text-gray-700">{fmtPrice(price)}</span> / kWh
{typeof c.priceVat === "number" ? ` (excl. ${c.priceVat}% btw)` : ""}
</div>
);
})()}
</div>
))}
</div>
)}
</div>
))}
</div>
</div>
)}
</>
)}
{!loading && !detail && (
<div className="text-sm text-gray-500 italic space-y-3">
<p>
Geen gedetailleerde informatie geladen voor deze locatie
{p.maxPowerKw > 0 ? ` (max. ${p.maxPowerKw} kW).` : "."}
</p>
{onJumpToGemeente && (
<button
onClick={onJumpToGemeente}
className="px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition not-italic"
>
Ga naar deze gemeente voor details
</button>
)}
</div>
)}
</div>
</div>
);
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex justify-between gap-2">
<span className="text-gray-600">{label}:</span>
<span className="text-right">{children}</span>
</div>
);
}
-462
View File
@@ -1,462 +0,0 @@
"use client";
import { useEffect, useState, useRef, useMemo, useCallback } from "react";
import Map, { NavigationControl, MapRef, Popup } from "react-map-gl/maplibre";
import { MapboxOverlay } from "@deck.gl/mapbox";
import { ScatterplotLayer, GeoJsonLayer } from "@deck.gl/layers";
import type { PickingInfo } from "@deck.gl/core";
import "maplibre-gl/dist/maplibre-gl.css";
import type { ChargeFeature, BoundaryFeature, Filters } from "@/types/charging";
import type { ChoroplethData, MetricMeta } from "@/types/analysis";
import { statusColor, freightColor, BOUNDARY_LINE, LEGEND, type RGBA } from "@/lib/colors";
import { rampColor, rampCss, robustDomain, NODATA } from "@/lib/ramp";
interface MapDeckProps {
chargeFeatures: ChargeFeature[];
boundaryFeatures: BoundaryFeature[];
bounds: [number, number, number, number] | null;
filters: Filters;
selectedLocationId: string | null;
onSelect: (feature: ChargeFeature | null) => void;
choropleth?: ChoroplethData | null;
analysisMetric?: string | null;
metricMeta?: MetricMeta | null;
onAreaSelect?: (props: Record<string, unknown>) => void;
}
interface AreaHover {
gemeente: string;
value: number | null;
lng: number;
lat: number;
}
const NL_BOUNDS: [[number, number], [number, number]] = [
[3.31, 50.75],
[7.21, 53.47],
];
const cursorStyle = (hovering: boolean) => `
.maplibregl-map, .maplibregl-canvas-container, .maplibregl-canvas {
cursor: ${hovering ? "pointer" : "default"} !important;
}
`;
export default function MapDeck({
chargeFeatures,
boundaryFeatures,
bounds,
filters,
selectedLocationId,
onSelect,
choropleth,
analysisMetric,
metricMeta,
onAreaSelect,
}: MapDeckProps) {
const mapRef = useRef<MapRef>(null);
const [deckOverlay, setDeckOverlay] = useState<MapboxOverlay | null>(null);
const [hovered, setHovered] = useState<ChargeFeature | null>(null);
const [areaHover, setAreaHover] = useState<AreaHover | null>(null);
const choroActive = !!(choropleth && analysisMetric);
const metricDomain = useMemo<[number, number] | null>(() => {
if (!choroActive) return null;
const vals = choropleth!.features
.map((f) => f.properties[analysisMetric!])
.filter((v): v is number => typeof v === "number");
return robustDomain(vals);
}, [choropleth, analysisMetric, choroActive]);
// Price coloring (mutually exclusive with the choropleth).
const priceActive = filters.colorByPrice && !choroActive;
const priceDomain = useMemo<[number, number] | null>(() => {
if (!priceActive) return null;
const vals = chargeFeatures
.map((f) => f.properties.priceKwh)
.filter((v): v is number => typeof v === "number");
return vals.length ? robustDomain(vals) : null;
}, [priceActive, chargeFeatures]);
const priceColor = useCallback(
(price: number | undefined): RGBA => {
if (typeof price !== "number" || !priceDomain) return NODATA as RGBA;
const [lo, hi] = priceDomain;
return rampColor(hi > lo ? (price - lo) / (hi - lo) : 0.5);
},
[priceDomain],
);
const fmtPrice = (v: number) =>
v.toLocaleString("nl-NL", { style: "currency", currency: "EUR", minimumFractionDigits: 2, maximumFractionDigits: 3 });
const fmt = (v: number) => {
const d = metricMeta?.decimals ?? 1;
return v.toLocaleString("nl-NL", { minimumFractionDigits: d, maximumFractionDigits: d });
};
useEffect(() => {
const overlay = new MapboxOverlay({ interleaved: true, layers: [] });
setDeckOverlay(overlay);
return () => overlay.finalize();
}, []);
// Split + power-filter the charge features once.
const { passenger, freight } = useMemo(() => {
const p: ChargeFeature[] = [];
const f: ChargeFeature[] = [];
for (const feat of chargeFeatures) {
if (feat.properties.maxPowerKw < filters.minPowerKw) continue;
if (feat.properties.layer === "freight") {
if (filters.dedicatedFreightOnly && feat.properties.freightKind === "hpc") continue;
f.push(feat);
} else p.push(feat);
}
return { passenger: p, freight: f };
}, [chargeFeatures, filters.minPowerKw, filters.dedicatedFreightOnly]);
const handleHover = useCallback((info: PickingInfo<ChargeFeature>) => {
setHovered(info.object ?? null);
}, []);
const handleClick = useCallback(
(info: PickingInfo<ChargeFeature>) => {
if (info.object) onSelect(info.object);
},
[onSelect],
);
const layers = useMemo(() => {
const result: unknown[] = [];
// Choropleth (analysis) underneath everything else.
if (choroActive && metricDomain) {
const [lo, hi] = metricDomain;
result.push(
new GeoJsonLayer({
id: "choropleth",
data: choropleth as never,
stroked: true,
filled: true,
getFillColor: (f: { properties: Record<string, unknown> }) => {
const v = f.properties[analysisMetric!];
if (typeof v !== "number") return NODATA as RGBA;
return rampColor(hi > lo ? (v - lo) / (hi - lo) : 0.5);
},
getLineColor: [255, 255, 255, 180] as RGBA,
lineWidthMinPixels: 0.5,
pickable: true,
onClick: (info: PickingInfo) => {
const o = info.object as { properties?: Record<string, unknown> } | null;
if (o?.properties && onAreaSelect) onAreaSelect(o.properties);
},
onHover: (info: PickingInfo) => {
const o = info.object as { properties?: Record<string, unknown> } | null;
if (o?.properties && info.coordinate) {
const v = o.properties[analysisMetric!];
setAreaHover({
gemeente: String(o.properties.gemeente ?? ""),
value: typeof v === "number" ? v : null,
lng: info.coordinate[0],
lat: info.coordinate[1],
});
} else {
setAreaHover(null);
}
},
updateTriggers: { getFillColor: [analysisMetric, lo, hi] },
}),
);
}
if (filters.showBoundary && boundaryFeatures.length) {
result.push(
new GeoJsonLayer({
id: "boundaries",
data: { type: "FeatureCollection", features: boundaryFeatures } as never,
stroked: true,
filled: false,
getLineColor: BOUNDARY_LINE as RGBA,
getLineWidth: 2,
lineWidthMinPixels: 1.5,
lineWidthMaxPixels: 3,
pickable: false,
}),
);
}
const scatterCommon = {
pickable: true,
stroked: true,
filled: true,
radiusUnits: "pixels" as const,
lineWidthMinPixels: 0.5,
getLineColor: [255, 255, 255, 230] as RGBA,
getLineWidth: 1,
onHover: handleHover,
onClick: handleClick,
getPosition: (d: ChargeFeature) => d.geometry.coordinates,
};
if (filters.showPassenger) {
result.push(
new ScatterplotLayer<ChargeFeature>({
...scatterCommon,
id: "passenger",
data: passenger,
radiusMinPixels: 3,
radiusMaxPixels: 10,
getRadius: (d) => (d.properties.locationId === selectedLocationId ? 11 : 5),
getFillColor: (d) => (priceActive ? priceColor(d.properties.priceKwh) : statusColor(d.properties.status)),
updateTriggers: { getRadius: [selectedLocationId], getFillColor: [priceActive, priceDomain] },
}),
);
}
if (filters.showFreight) {
result.push(
new ScatterplotLayer<ChargeFeature>({
...scatterCommon,
id: "freight",
data: freight,
radiusMinPixels: 5,
radiusMaxPixels: 16,
getRadius: (d) =>
d.properties.locationId === selectedLocationId
? 16
: d.properties.isMegawatt
? 11
: d.properties.freightKind === "hpc"
? 6
: 8,
getFillColor: (d) =>
priceActive ? priceColor(d.properties.priceKwh) : freightColor(d.properties.isMegawatt, d.properties.freightKind),
// Ring encodes live OCPI status (freight fill stays amber for identity).
getLineColor: (d) =>
d.properties.status === "UNKNOWN"
? ([255, 255, 255, 230] as RGBA)
: (statusColor(d.properties.status).slice(0, 3).concat(255) as RGBA),
getLineWidth: (d) => (d.properties.isMegawatt ? 2.5 : 1.5),
updateTriggers: { getRadius: [selectedLocationId], getFillColor: [priceActive, priceDomain] },
}),
);
}
return result;
}, [
passenger,
freight,
boundaryFeatures,
filters.showPassenger,
filters.showFreight,
filters.showBoundary,
selectedLocationId,
handleHover,
handleClick,
choroActive,
choropleth,
analysisMetric,
metricDomain,
priceActive,
priceColor,
priceDomain,
onAreaSelect,
]);
useEffect(() => {
if (deckOverlay) deckOverlay.setProps({ layers: layers as never });
}, [deckOverlay, layers]);
// Fit to bounds whenever they change (municipality selection).
useEffect(() => {
if (bounds && mapRef.current) {
mapRef.current.fitBounds(
[
[bounds[0], bounds[1]],
[bounds[2], bounds[3]],
],
{ padding: 40, duration: 800 },
);
}
}, [bounds]);
const onMapLoad = useCallback(() => {
if (mapRef.current && deckOverlay) {
mapRef.current.getMap().addControl(deckOverlay as never);
}
}, [deckOverlay]);
return (
<div className="h-full w-full relative">
<style>{cursorStyle(!!hovered || !!areaHover)}</style>
<Map
ref={mapRef}
initialViewState={{ longitude: 5.2913, latitude: 52.1326, zoom: 7 }}
style={{ width: "100%", height: "100%" }}
mapStyle="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
maxBounds={NL_BOUNDS}
onLoad={onMapLoad}
>
<NavigationControl position="top-right" />
{hovered && (
<Popup
longitude={hovered.geometry.coordinates[0]}
latitude={hovered.geometry.coordinates[1]}
closeButton={false}
closeOnClick={false}
anchor="bottom"
offset={12}
>
<div className="p-2 max-w-xs">
<div className="font-semibold text-sm text-gray-900">{hovered.properties.name}</div>
{hovered.properties.city && (
<div className="text-xs text-gray-600">{hovered.properties.city}</div>
)}
{hovered.properties.operatorName && (
<div className="text-xs text-gray-500 italic">{hovered.properties.operatorName}</div>
)}
<div className="text-xs mt-1 flex items-center gap-2">
<span
className="inline-block px-1.5 py-0.5 rounded text-white"
style={{
background:
hovered.properties.layer === "freight"
? hovered.properties.isMegawatt
? LEGEND.freightMegawatt
: hovered.properties.freightKind === "hpc"
? LEGEND.freightHpc
: LEGEND.freight
: LEGEND[
(
{
AVAILABLE: "available",
CHARGING: "charging",
UNAVAILABLE: "unavailable",
UNKNOWN: "unknown",
} as const
)[hovered.properties.status] ?? "unknown"
],
}}
>
{hovered.properties.layer === "freight"
? hovered.properties.freightKind === "hpc"
? "Truck-capable ≥350 kW"
: "Truck"
: "Personenauto"}
</span>
{hovered.properties.maxPowerKw > 0 && <span>{hovered.properties.maxPowerKw} kW</span>}
</div>
{typeof hovered.properties.priceKwh === "number" && (
<div className="text-xs mt-1 text-gray-700">
Tarief: <span className="font-medium">{fmtPrice(hovered.properties.priceKwh)}</span> / kWh
</div>
)}
<div className="text-xs text-blue-600 mt-1">Klik voor details</div>
</div>
</Popup>
)}
{/* Choropleth area hover */}
{choroActive && areaHover && (
<Popup
longitude={areaHover.lng}
latitude={areaHover.lat}
closeButton={false}
closeOnClick={false}
anchor="bottom"
offset={8}
>
<div className="p-2">
<div className="font-semibold text-sm text-gray-900">{areaHover.gemeente}</div>
<div className="text-xs text-gray-600">
{metricMeta?.label}:{" "}
<span className="font-medium">
{areaHover.value === null ? "geen data" : `${fmt(areaHover.value)}${metricMeta?.unit ? " " + metricMeta.unit : ""}`}
</span>
</div>
</div>
</Popup>
)}
</Map>
{/* Choropleth legend */}
{choroActive && metricDomain && (
<div className="absolute bottom-4 left-4 bg-white/90 backdrop-blur-sm rounded-lg p-3 shadow-md text-xs">
<div className="font-semibold mb-1">{metricMeta?.label}</div>
<div
className="h-2 w-40 rounded"
style={{ background: `linear-gradient(to right, ${rampCss(0)}, ${rampCss(0.25)}, ${rampCss(0.5)}, ${rampCss(0.75)}, ${rampCss(1)})` }}
/>
<div className="flex justify-between w-40 text-gray-500 mt-0.5">
<span>{fmt(metricDomain[0])}</span>
<span>{fmt(metricDomain[1])}{metricMeta?.unit ? ` ${metricMeta.unit}` : ""}</span>
</div>
<div className="flex items-center gap-1 mt-1 text-gray-400">
<span className="w-3 h-3 rounded-sm" style={{ background: "rgb(226,232,240)" }} />
geen data
</div>
</div>
)}
{/* Price legend */}
{priceActive && priceDomain && (
<div className="absolute bottom-4 left-4 bg-white/90 backdrop-blur-sm rounded-lg p-3 shadow-md text-xs">
<div className="font-semibold mb-1">Tarief (€/kWh)</div>
<div
className="h-2 w-40 rounded"
style={{ background: `linear-gradient(to right, ${rampCss(0)}, ${rampCss(0.25)}, ${rampCss(0.5)}, ${rampCss(0.75)}, ${rampCss(1)})` }}
/>
<div className="flex justify-between w-40 text-gray-500 mt-0.5">
<span>{fmtPrice(priceDomain[0])}</span>
<span>{fmtPrice(priceDomain[1])}</span>
</div>
<div className="flex items-center gap-1 mt-1 text-gray-400">
<span className="w-3 h-3 rounded-sm" style={{ background: "rgb(226,232,240)" }} />
geen tarief
</div>
</div>
)}
{/* Marker legend */}
{!choroActive && !priceActive && (
<div data-tour="legend" className="absolute bottom-4 left-4 bg-white/90 backdrop-blur-sm rounded-lg p-3 shadow-md text-xs">
<div className="font-semibold mb-1">Personenauto (status)</div>
<div className="space-y-1">
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.available }} />
<span>Beschikbaar</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.charging }} />
<span>Bezet (laden)</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.unavailable }} />
<span>Niet beschikbaar</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.unknown }} />
<span>Onbekend</span>
</div>
</div>
<div className="font-semibold mt-2 mb-1">Logistiek / vracht</div>
<div className="space-y-1">
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.freight }} />
<span>Dedicated truck-locatie</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.freightHpc }} />
<span>Truck-capable ≥350 kW</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.freightMegawatt }} />
<span>Megawatt charging (MCS)</span>
</div>
<div className="text-gray-400">rand = status (groen/blauw/rood)</div>
</div>
</div>
)}
</div>
);
}
-312
View File
@@ -1,312 +0,0 @@
'use client';
import { useState, useMemo, useRef, useEffect } from 'react';
import { Municipality } from '@/types/charging';
interface MunicipalitySelectorProps {
municipalities: Municipality[];
selected: string;
onChange: (slug: string) => void;
}
type SortOrder = 'asc' | 'desc';
export default function MunicipalitySelector({
municipalities,
selected,
onChange,
}: MunicipalitySelectorProps) {
const [searchTerm, setSearchTerm] = useState('');
const [showDropdown, setShowDropdown] = useState(false);
const [sortOrder, setSortOrder] = useState<SortOrder>('asc');
const [highlightedIndex, setHighlightedIndex] = useState(-1);
const containerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
// Get selected municipality display name
const selectedMunicipality = municipalities.find(m => m.slug === selected);
const displayValue = selectedMunicipality
? `${selectedMunicipality.name} (${selectedMunicipality.province})`
: '';
// Get Nederland separately (always shown as sticky footer)
const nederland = useMemo(() =>
municipalities.find(m => m.slug === 'nederland'),
[municipalities]
);
// Sort and filter municipalities (excluding Nederland)
const filteredMunicipalities = useMemo(() => {
// Exclude Nederland from regular list (it will be sticky at bottom)
let filtered = municipalities.filter(m => m.slug !== 'nederland');
// Filter by search term
if (searchTerm) {
filtered = filtered.filter(m =>
m.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
m.province.toLowerCase().includes(searchTerm.toLowerCase())
);
}
// Sort alphabetically
filtered = [...filtered].sort((a, b) => {
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
return sortOrder === 'asc'
? nameA.localeCompare(nameB)
: nameB.localeCompare(nameA);
});
return filtered;
}, [municipalities, searchTerm, sortOrder]);
// Reset highlighted index when search term or dropdown visibility changes
useEffect(() => {
setHighlightedIndex(-1);
}, [searchTerm, showDropdown]);
// Scroll highlighted item into view
useEffect(() => {
if (highlightedIndex >= 0 && dropdownRef.current) {
const highlightedElement = dropdownRef.current.querySelector(
`[data-index="${highlightedIndex}"]`
);
if (highlightedElement) {
highlightedElement.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
}
}, [highlightedIndex]);
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setShowDropdown(false);
setSearchTerm('');
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// Global keyboard shortcut (Cmd/Ctrl + K) to focus search
useEffect(() => {
const handleGlobalKeydown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
inputRef.current?.focus();
setShowDropdown(true);
}
};
document.addEventListener('keydown', handleGlobalKeydown);
return () => document.removeEventListener('keydown', handleGlobalKeydown);
}, []);
const handleSelect = (slug: string) => {
onChange(slug);
setShowDropdown(false);
setSearchTerm('');
setHighlightedIndex(-1);
};
const toggleSort = () => {
setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc');
};
// Keyboard navigation
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (!showDropdown) {
// Open dropdown on ArrowDown when closed
if (e.key === 'ArrowDown') {
e.preventDefault();
setShowDropdown(true);
}
return;
}
// Total items including sticky Nederland
const totalItems = filteredMunicipalities.length + (nederland ? 1 : 0);
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setHighlightedIndex(prev =>
prev < totalItems - 1 ? prev + 1 : prev
);
break;
case 'ArrowUp':
e.preventDefault();
setHighlightedIndex(prev => (prev > 0 ? prev - 1 : -1));
break;
case 'Enter':
e.preventDefault();
if (highlightedIndex >= 0 && highlightedIndex < filteredMunicipalities.length) {
handleSelect(filteredMunicipalities[highlightedIndex].slug);
} else if (highlightedIndex === filteredMunicipalities.length && nederland) {
// Nederland is selected (sticky footer)
handleSelect(nederland.slug);
} else if (filteredMunicipalities.length === 1) {
// Auto-select if only one result
handleSelect(filteredMunicipalities[0].slug);
}
break;
case 'Escape':
e.preventDefault();
setShowDropdown(false);
setSearchTerm('');
setHighlightedIndex(-1);
inputRef.current?.blur();
break;
case 'Tab':
// Close dropdown on Tab
setShowDropdown(false);
setSearchTerm('');
setHighlightedIndex(-1);
break;
}
};
return (
<div className="relative" ref={containerRef}>
<div className="relative">
<input
ref={inputRef}
type="text"
id="municipality"
value={showDropdown ? searchTerm : displayValue}
onChange={(e) => {
setSearchTerm(e.target.value);
setShowDropdown(true);
}}
onFocus={() => setShowDropdown(true)}
onKeyDown={handleKeyDown}
placeholder={selectedMunicipality ? displayValue : "Selecteer gemeente..."}
className="w-full px-3 md:px-4 py-2.5 md:py-2 pr-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 text-sm"
autoComplete="off"
role="combobox"
aria-autocomplete="list"
aria-expanded={showDropdown}
aria-controls="municipality-listbox"
aria-activedescendant={
highlightedIndex >= 0 ? `municipality-option-${highlightedIndex}` : undefined
}
/>
<div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</div>
{showDropdown && (
<div
ref={dropdownRef}
id="municipality-listbox"
role="listbox"
className="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-[60vh] md:max-h-96 overflow-y-auto"
>
{/* Header */}
<div className="sticky top-0 bg-gray-50 px-3 py-2 text-xs text-gray-500 border-b flex items-center justify-between z-10">
<span>{filteredMunicipalities.length} gemeentes</span>
<div className="flex items-center gap-2">
<kbd className="hidden md:inline-block px-1.5 py-0.5 text-xs font-mono bg-white border border-gray-300 rounded">
⌘K
</kbd>
<button
onClick={toggleSort}
className="text-blue-600 hover:text-blue-800 flex items-center gap-1 p-1 -m-1"
title={sortOrder === 'asc' ? 'Sorteer Z-A' : 'Sorteer A-Z'}
tabIndex={-1}
>
{sortOrder === 'asc' ? 'A-Z' : 'Z-A'}
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={sortOrder === 'asc' ? "M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12" : "M3 4h13M3 8h9m-9 4h9m5-4v12m0 0l-4-4m4 4l4-4"} />
</svg>
</button>
</div>
</div>
{/* Municipality list */}
{filteredMunicipalities.length > 0 ? (
filteredMunicipalities.map((m, index) => (
<button
key={m.slug}
id={`municipality-option-${index}`}
role="option"
aria-selected={m.slug === selected}
data-index={index}
onClick={() => handleSelect(m.slug)}
onMouseEnter={() => setHighlightedIndex(index)}
className={`w-full text-left px-3 md:px-4 py-3 md:py-2 transition-colors ${
index === highlightedIndex
? 'bg-blue-100'
: m.slug === selected
? 'bg-blue-50'
: 'hover:bg-gray-50 active:bg-gray-100'
}`}
tabIndex={-1}
>
<div className="flex items-center justify-between">
<div>
<div className="text-sm font-medium text-gray-900">{m.name}</div>
<div className="text-xs text-gray-500">{m.province}</div>
</div>
{m.slug === selected && (
<svg className="w-4 h-4 text-blue-600 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
</svg>
)}
</div>
</button>
))
) : (
<div className="px-4 py-6 md:py-8 text-center text-sm text-gray-500">
Geen gemeentes gevonden voor &quot;{searchTerm}&quot;
</div>
)}
{/* Sticky Nederland footer */}
{nederland && (
<div className="sticky bottom-0 border-t border-gray-200 bg-white shadow-[0_-2px_4px_rgba(0,0,0,0.05)]">
<button
id={`municipality-option-nederland`}
role="option"
aria-selected={nederland.slug === selected}
data-index={filteredMunicipalities.length}
onClick={() => handleSelect(nederland.slug)}
onMouseEnter={() => setHighlightedIndex(filteredMunicipalities.length)}
className={`w-full text-left px-3 md:px-4 py-3 md:py-2 transition-colors ${
highlightedIndex === filteredMunicipalities.length
? 'bg-blue-100'
: nederland.slug === selected
? 'bg-blue-50'
: 'hover:bg-gray-50 active:bg-gray-100'
}`}
tabIndex={-1}
>
<div className="flex items-center justify-between">
<div>
<div className="text-sm font-medium text-gray-900">{nederland.name}</div>
<div className="text-xs text-gray-500">Landelijk overzicht</div>
</div>
{nederland.slug === selected && (
<svg className="w-4 h-4 text-blue-600 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
</svg>
)}
</div>
</button>
</div>
)}
</div>
)}
</div>
</div>
);
}
-82
View File
@@ -1,82 +0,0 @@
"use client";
import { useState } from "react";
import { X, Copy, Check } from "lucide-react";
interface Props {
isOpen: boolean;
onClose: () => void;
municipality: string;
municipalityName: string;
}
export default function ShareModal({ isOpen, onClose, municipality, municipalityName }: Props) {
const [copied, setCopied] = useState<string | null>(null);
if (!isOpen) return null;
const origin = typeof window !== "undefined" ? window.location.origin : "";
const slug = municipality === "nederland" ? "alle-gemeenten" : municipality;
const shareUrl = `${origin}/?gemeente=${slug}`;
const embedCode = `<iframe src="${origin}/embed?gemeente=${slug}" width="100%" height="600" style="border:0" title="Laadpalenviewer ${municipalityName}"></iframe>`;
const copy = (text: string, key: string) => {
navigator.clipboard.writeText(text);
setCopied(key);
setTimeout(() => setCopied(null), 1500);
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
<div className="bg-white rounded-lg shadow-xl max-w-lg w-full" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-lg font-semibold">Delen — {municipalityName}</h2>
<button onClick={onClose} className="p-1 hover:bg-gray-100 rounded">
<X className="h-5 w-5" />
</button>
</div>
<div className="p-4 space-y-4 text-sm">
<Field label="Link" value={shareUrl} copied={copied === "url"} onCopy={() => copy(shareUrl, "url")} />
<Field label="Embed-code" value={embedCode} copied={copied === "embed"} onCopy={() => copy(embedCode, "embed")} multiline />
</div>
</div>
</div>
);
}
function Field({
label,
value,
copied,
onCopy,
multiline,
}: {
label: string;
value: string;
copied: boolean;
onCopy: () => void;
multiline?: boolean;
}) {
return (
<div>
<label className="block text-xs font-medium text-gray-600 mb-1">{label}</label>
<div className="flex gap-2">
{multiline ? (
<textarea
readOnly
value={value}
rows={3}
className="flex-1 px-2 py-1.5 border border-gray-300 rounded text-xs font-mono resize-none"
/>
) : (
<input readOnly value={value} className="flex-1 px-2 py-1.5 border border-gray-300 rounded text-xs" />
)}
<button
onClick={onCopy}
className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded flex items-center gap-1 text-xs"
>
{copied ? <Check className="h-4 w-4 text-green-600" /> : <Copy className="h-4 w-4" />}
</button>
</div>
</div>
);
}
-122
View File
@@ -1,122 +0,0 @@
"use client";
import { useMemo } from "react";
import type { ChargeFeature } from "@/types/charging";
import { LEGEND } from "@/lib/colors";
import InfoTip from "@/components/InfoTip";
interface StatsPanelProps {
gemeente: string;
chargeFeatures: ChargeFeature[];
}
export default function StatsPanel({ gemeente, chargeFeatures }: StatsPanelProps) {
const stats = useMemo(() => {
let passenger = 0;
let freight = 0;
let freightDedicated = 0;
let megawatt = 0;
let available = 0;
let charging = 0;
let unavailable = 0;
const operators = new Map<string, number>();
for (const f of chargeFeatures) {
const p = f.properties;
if (p.layer === "freight") {
freight++;
if (p.freightKind !== "hpc") freightDedicated++;
if (p.isMegawatt) megawatt++;
} else {
passenger++;
// Status tallies match the map, which only colors passenger points by status.
if (p.status === "AVAILABLE") available++;
else if (p.status === "CHARGING") charging++;
else if (p.status === "UNAVAILABLE") unavailable++;
}
if (p.operatorName) operators.set(p.operatorName, (operators.get(p.operatorName) ?? 0) + 1);
}
const topOperators = [...operators.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5);
return { passenger, freight, freightDedicated, megawatt, available, charging, unavailable, topOperators };
}, [chargeFeatures]);
return (
<div className="bg-white rounded-lg shadow-sm p-4 space-y-3">
<h3 className="text-sm font-semibold text-gray-900 truncate">{gemeente}</h3>
<div className="grid grid-cols-2 gap-2">
<div className="bg-blue-50 rounded-lg p-2">
<div className="text-xl font-bold text-blue-700 tabular-nums">
{stats.passenger.toLocaleString("nl-NL")}
</div>
<div className="text-xs text-blue-900">Personenauto</div>
</div>
<div className="bg-amber-50 rounded-lg p-2">
<div className="text-xl font-bold text-amber-700 tabular-nums">
{stats.freight.toLocaleString("nl-NL")}
</div>
<div className="text-xs text-amber-900 flex items-center gap-1">
Logistiek / vracht
<InfoTip title="Logistiek / vracht">
Truck-laadlocaties: <strong>dedicated</strong> voorzieningen (truck-exploitant zoals
Milence/WattHub, “truck” in de naam, MCS-aansluiting, of een logistiek depot met ≥150 kW DC)
plus <strong>truck-capable</strong> snelladers met ≥350 kW DC die niet aantoonbaar op trucks
zijn ingericht.
</InfoTip>
</div>
</div>
</div>
{stats.freight > 0 && (
<div className="text-xs text-amber-800 bg-amber-50 rounded px-2 py-1">
{stats.freightDedicated} dedicated · {stats.freight - stats.freightDedicated} truck-capable ≥350 kW
</div>
)}
{stats.megawatt > 0 && (
<div className="text-xs text-orange-700 bg-orange-50 rounded px-2 py-1">
waarvan {stats.megawatt} megawatt-locatie{stats.megawatt !== 1 ? "s" : ""}
</div>
)}
{/* OCPI status breakdown */}
<div>
<div className="text-xs font-medium text-gray-600 mb-1 flex items-center gap-1">
Status personenauto (OCPI-momentopname)
<InfoTip title="OCPI-status">
Beschikbaar/bezet/niet-beschikbaar komt uit de OCPI-status in de laatste uurlijkse momentopname van
de NDW-data — een snapshot, geen continue realtime stream. “Bezet” = connector aan het laden.
Telt alleen personenauto-punten; bij truckpunten zit de status in de ringkleur op de kaart.
</InfoTip>
</div>
<div className="flex flex-wrap gap-x-3 gap-y-1 text-xs">
<StatusChip color={LEGEND.available} label="Beschikbaar" value={stats.available} />
<StatusChip color={LEGEND.charging} label="Bezet" value={stats.charging} />
<StatusChip color={LEGEND.unavailable} label="Niet besch." value={stats.unavailable} />
</div>
</div>
{stats.topOperators.length > 0 && (
<div>
<div className="text-xs font-medium text-gray-600 mb-1">Grootste exploitanten</div>
<ul className="space-y-1">
{stats.topOperators.map(([name, count]) => (
<li key={name} className="flex items-center justify-between text-xs text-gray-700">
<span className="truncate pr-2">{name}</span>
<span className="text-gray-400 tabular-nums">{count.toLocaleString("nl-NL")}</span>
</li>
))}
</ul>
</div>
)}
</div>
);
}
function StatusChip({ color, label, value }: { color: string; label: string; value: number }) {
return (
<span className="flex items-center gap-1 text-gray-700">
<span className="w-2.5 h-2.5 rounded-full" style={{ background: color }} />
{label}
<span className="text-gray-400 tabular-nums">{value.toLocaleString("nl-NL")}</span>
</span>
);
}
-224
View File
@@ -1,224 +0,0 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import InfoTip from "@/components/InfoTip";
// Per-day snapshot file shape (data/snapshots/<slug>/<date>.json)
interface DayFile {
date: string;
tz: string;
locations: Record<string, { n: number; occ: (number | null)[] }>;
}
// Daily-averages file shape (data/snapshots/<slug>/daily.json)
type DailyFile = Record<string, Record<string, number>>;
type Range = "24h" | "7d" | "30d" | "1y";
const RANGES: { key: Range; label: string }[] = [
{ key: "24h", label: "24u" },
{ key: "7d", label: "7d" },
{ key: "30d", label: "30d" },
{ key: "1y", label: "1j" },
];
interface Point {
label: string; // x tooltip label
short: string; // x-axis tick
v: number | null; // occupancy %
}
// Europe/Amsterdam local date (YYYY-MM-DD), `offset` days ago.
function localDate(offsetDays: number): string {
const d = new Date();
d.setDate(d.getDate() - offsetDays);
return new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Amsterdam",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(d);
}
async function getJson<T>(url: string): Promise<T | null> {
try {
const r = await fetch(url);
return r.ok ? ((await r.json()) as T) : null;
} catch {
return null;
}
}
export default function UsageChart({ slug, locationId }: { slug: string; locationId: string }) {
const [range, setRange] = useState<Range>("24h");
const [points, setPoints] = useState<Point[] | null>(null);
const [loading, setLoading] = useState(true);
const [hover, setHover] = useState<number | null>(null);
useEffect(() => {
let cancelled = false;
setLoading(true);
setPoints(null);
setHover(null);
const build = async (): Promise<Point[]> => {
if (range === "1y") {
const daily = await getJson<DailyFile>(`/data/snapshots/${slug}/daily.json`);
const series = daily?.[locationId] ?? {};
const dates = Object.keys(series).sort();
return dates.map((d) => ({ label: d, short: d.slice(5), v: series[d] }));
}
const days = range === "24h" ? 1 : range === "7d" ? 7 : 30;
const dates: string[] = [];
for (let i = days - 1; i >= 0; i--) dates.push(localDate(i));
const files = await Promise.all(dates.map((d) => getJson<DayFile>(`/data/snapshots/${slug}/${d}.json`)));
const out: Point[] = [];
files.forEach((f, di) => {
const occ = f?.locations?.[locationId]?.occ ?? Array(24).fill(null);
for (let h = 0; h < 24; h++) {
out.push({
label: `${dates[di]} ${String(h).padStart(2, "0")}:00`,
short: range === "24h" ? `${h}u` : h === 12 ? dates[di].slice(5) : "",
v: occ[h] ?? null,
});
}
});
return out;
};
build()
.then((p) => {
if (!cancelled) setPoints(p);
})
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [slug, locationId, range]);
const stats = useMemo(() => {
if (!points) return null;
const vals = points.map((p) => p.v).filter((v): v is number => v !== null);
if (vals.length === 0) return { avg: null, hasData: false };
return { avg: Math.round(vals.reduce((a, b) => a + b, 0) / vals.length), hasData: true };
}, [points]);
// Build SVG polyline segments (break on nulls).
const segments = useMemo(() => {
if (!points || points.length === 0) return [];
const n = points.length;
const segs: string[] = [];
let cur: string[] = [];
points.forEach((p, i) => {
if (p.v === null) {
if (cur.length) segs.push(cur.join(" "));
cur = [];
return;
}
const x = n === 1 ? 50 : (i / (n - 1)) * 100;
const y = 100 - Math.min(100, Math.max(0, p.v));
cur.push(`${x.toFixed(2)},${y.toFixed(2)}`);
});
if (cur.length) segs.push(cur.join(" "));
return segs;
}, [points]);
return (
<div className="space-y-2" data-tour="usage">
<div className="flex items-center justify-between">
<h4 className="font-medium text-sm text-gray-700 flex items-center gap-1">
Gebruik over de tijd
<InfoTip title="Gebruik over de tijd">
Per uur: het aandeel connectoren van deze locatie met OCPI-status “laden” (% in gebruik). Opgebouwd
uit de uurlijkse NDW-snapshots; 24u/7d/30d tonen uurwaarden, 1j toont daggemiddelden. De historie
groeit naarmate de app langer draait.
</InfoTip>
</h4>
<div className="flex gap-1">
{RANGES.map((r) => (
<button
key={r.key}
onClick={() => setRange(r.key)}
className={`px-1.5 py-0.5 text-[11px] rounded ${
range === r.key ? "bg-blue-600 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"
}`}
>
{r.label}
</button>
))}
</div>
</div>
{loading ? (
<div className="h-28 bg-gray-100 rounded animate-pulse" />
) : !stats?.hasData ? (
<p className="text-xs text-gray-400">Nog geen gebruiksdata voor deze locatie.</p>
) : (
<div className="bg-gray-50 rounded p-2">
<div className="flex">
<div className="flex flex-col justify-between h-28 pr-1 text-[9px] text-gray-400 text-right">
<span>100%</span>
<span>50%</span>
<span>0%</span>
</div>
<div
className="relative flex-1 h-28"
onMouseLeave={() => setHover(null)}
onMouseMove={(e) => {
const rect = e.currentTarget.getBoundingClientRect();
const ratio = (e.clientX - rect.left) / rect.width;
const idx = Math.round(ratio * ((points?.length ?? 1) - 1));
setHover(Math.max(0, Math.min((points?.length ?? 1) - 1, idx)));
}}
>
{/* grid */}
{[0, 50, 100].map((g) => (
<div key={g} className="absolute left-0 right-0 border-t border-gray-200" style={{ top: `${g}%` }} />
))}
{/* average line */}
{stats.avg !== null && (
<div
className="absolute left-0 right-0 border-t border-dashed border-blue-400/70"
style={{ top: `${100 - stats.avg}%` }}
>
<span className="absolute right-0 -top-3 text-[9px] text-blue-500 bg-gray-50 px-0.5">
gem. {stats.avg}%
</span>
</div>
)}
<svg className="absolute inset-0 w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
{segments.map((pts, i) =>
pts.includes(" ") ? (
<polyline key={i} points={pts} fill="none" stroke="#2563eb" strokeWidth="1.2" vectorEffect="non-scaling-stroke" />
) : (
<circle key={i} cx={pts.split(",")[0]} cy={pts.split(",")[1]} r="1.5" fill="#2563eb" vectorEffect="non-scaling-stroke" />
),
)}
</svg>
{/* hover marker */}
{hover !== null && points && points[hover]?.v !== null && (
<div
className="absolute z-10 -translate-x-1/2 -translate-y-full bg-gray-800 text-white text-[9px] px-1 py-0.5 rounded whitespace-nowrap pointer-events-none"
style={{
left: `${points.length === 1 ? 50 : (hover / (points.length - 1)) * 100}%`,
top: `${100 - (points[hover].v as number)}%`,
}}
>
{points[hover].label} — {points[hover].v}%
</div>
)}
</div>
</div>
{/* x-axis ticks */}
<div className="flex justify-between mt-1 pl-6 text-[8px] text-gray-400">
{points &&
points
.map((p, i) => ({ p, i }))
.filter(({ p }) => p.short)
.filter((_, idx, arr) => arr.length <= 12 || idx % Math.ceil(arr.length / 12) === 0)
.map(({ p, i }) => <span key={i}>{p.short}</span>)}
</div>
<p className="text-[10px] text-gray-400 mt-1">% connectoren in gebruik (laden), OCPI-momentopname per uur.</p>
</div>
)}
</div>
);
}
-12
View File
@@ -1,12 +0,0 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({ baseDirectory: __dirname });
const eslintConfig = [...compat.extends("next/core-web-vitals", "next/typescript")];
export default eslintConfig;
-47
View File
@@ -1,47 +0,0 @@
// Color palettes for the deck.gl layers and legend.
import type { AggregateStatus } from "@/types/charging";
export type RGBA = [number, number, number, number];
// Passenger points: colored by OCPI status (fleetsim-style).
export const STATUS_AVAILABLE: RGBA = [34, 197, 94, 210]; // green-500
export const STATUS_CHARGING: RGBA = [59, 130, 246, 210]; // blue-500
export const STATUS_UNAVAILABLE: RGBA = [239, 68, 68, 210]; // red-500
export const STATUS_UNKNOWN: RGBA = [107, 114, 128, 200]; // gray-500
// Freight points: amber/orange; megawatt = red-orange; truck-capable HPC = light amber.
export const FREIGHT: RGBA = [245, 158, 11, 235]; // amber-500
export const FREIGHT_MEGAWATT: RGBA = [234, 88, 12, 245]; // orange-600
export const FREIGHT_HPC: RGBA = [252, 211, 77, 220]; // amber-300
export const BOUNDARY_LINE: RGBA = [79, 70, 229, 200]; // indigo-600
export function statusColor(status: AggregateStatus): RGBA {
switch (status) {
case "AVAILABLE":
return STATUS_AVAILABLE;
case "CHARGING":
return STATUS_CHARGING;
case "UNAVAILABLE":
return STATUS_UNAVAILABLE;
default:
return STATUS_UNKNOWN;
}
}
export function freightColor(isMegawatt: boolean, kind?: string): RGBA {
if (isMegawatt) return FREIGHT_MEGAWATT;
return kind === "hpc" ? FREIGHT_HPC : FREIGHT;
}
// Hex equivalents for legend / UI swatches.
export const LEGEND = {
available: "#22c55e",
charging: "#3b82f6",
unavailable: "#ef4444",
unknown: "#6b7280",
freight: "#f59e0b",
freightMegawatt: "#ea580c",
freightHpc: "#fcd34d",
boundary: "#4f46e5",
};
-62
View File
@@ -1,62 +0,0 @@
// Human-readable labels for OCPI connector/EVSE fields.
// Lifted from fleetsim's ChargingPointsMapDeck helpers.
const CONNECTOR_LABELS: Record<string, string> = {
IEC_62196_T2: "Type 2",
IEC_62196_T2_COMBO: "CCS (Type 2 Combo)",
CHADEMO: "CHAdeMO",
DOMESTIC_A: "Schuko",
DOMESTIC_F: "Type F (Schuko)",
DOMESTIC_G: "Type G (UK)",
IEC_60309_2_single_16: "IEC 60309 (16A)",
IEC_60309_2_three_16: "IEC 60309 3-fase (16A)",
IEC_60309_2_three_32: "IEC 60309 3-fase (32A)",
IEC_60309_2_three_64: "IEC 60309 3-fase (64A)",
TESLA_S: "Tesla (Type 2)",
IEC_63379: "MCS (Megawatt)",
};
export function formatConnectorStandard(standard: string): string {
if (CONNECTOR_LABELS[standard]) return CONNECTOR_LABELS[standard];
if (standard?.toUpperCase().startsWith("MCS")) return "MCS (Megawatt)";
return standard;
}
const POWER_TYPE_LABELS: Record<string, string> = {
AC_1_PHASE: "AC 1-fase",
AC_3_PHASE: "AC 3-fase",
DC: "DC",
};
export function formatPowerType(powerType: string): string {
return POWER_TYPE_LABELS[powerType] || powerType;
}
export function statusColorClass(status: string): string {
switch (status) {
case "AVAILABLE":
return "bg-green-500";
case "CHARGING":
return "bg-blue-500";
case "BLOCKED":
return "bg-orange-500";
case "OUTOFORDER":
return "bg-red-500";
case "RESERVED":
return "bg-purple-500";
default:
return "bg-gray-500";
}
}
export function statusLabel(status: string): string {
const labels: Record<string, string> = {
AVAILABLE: "Beschikbaar",
CHARGING: "Bezet",
BLOCKED: "Geblokkeerd",
OUTOFORDER: "Buiten dienst",
RESERVED: "Gereserveerd",
UNKNOWN: "Onbekend",
};
return labels[status] || status;
}
-40
View File
@@ -1,40 +0,0 @@
// Locate the gemeente (by slug) whose polygon contains a point, using the
// analysis choropleth as the polygon source. Ray casting; holes respected.
import type { ChoroplethData } from "@/types/analysis";
function inRing(ring: number[][], lng: number, lat: number): boolean {
let inside = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const [xi, yi] = ring[i];
const [xj, yj] = ring[j];
if (yi > lat !== yj > lat && lng < ((xj - xi) * (lat - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
function inPolygon(coords: number[][][], lng: number, lat: number): boolean {
if (!coords.length || !inRing(coords[0], lng, lat)) return false;
for (let k = 1; k < coords.length; k++) {
if (inRing(coords[k], lng, lat)) return false; // inside a hole
}
return true;
}
export function findGemeenteSlug(
choropleth: ChoroplethData | null,
lng: number,
lat: number,
): string | null {
if (!choropleth) return null;
for (const f of choropleth.features) {
const g = f.geometry;
const hit =
g.type === "Polygon"
? inPolygon(g.coordinates as number[][][], lng, lat)
: g.type === "MultiPolygon"
? (g.coordinates as number[][][][]).some((p) => inPolygon(p, lng, lat))
: false;
if (hit) return f.properties.slug ?? null;
}
return null;
}
-42
View File
@@ -1,42 +0,0 @@
// Sequential color ramp (YlOrRd-ish) for choropleths.
export type RGBA = [number, number, number, number];
const STOPS: [number, number, number][] = [
[255, 255, 204],
[254, 217, 118],
[253, 141, 60],
[240, 59, 32],
[189, 0, 38],
];
export const NODATA: RGBA = [226, 232, 240, 120]; // slate-200, translucent
export function rampColor(t: number, alpha = 200): RGBA {
const x = Math.min(1, Math.max(0, t));
const seg = x * (STOPS.length - 1);
const i = Math.min(STOPS.length - 2, Math.floor(seg));
const f = seg - i;
const a = STOPS[i];
const b = STOPS[i + 1];
return [
Math.round(a[0] + (b[0] - a[0]) * f),
Math.round(a[1] + (b[1] - a[1]) * f),
Math.round(a[2] + (b[2] - a[2]) * f),
alpha,
];
}
export function rampCss(t: number): string {
const [r, g, b] = rampColor(t, 255);
return `rgb(${r},${g},${b})`;
}
// Robust domain [p5, p95] over numeric values.
export function robustDomain(values: number[]): [number, number] {
const v = values.filter((x) => Number.isFinite(x)).sort((a, b) => a - b);
if (v.length === 0) return [0, 1];
const at = (p: number) => v[Math.min(v.length - 1, Math.max(0, Math.floor(p * (v.length - 1))))];
const lo = at(0.05);
const hi = at(0.95);
return hi > lo ? [lo, hi] : [v[0], v[v.length - 1] || v[0] + 1];
}
-71
View File
@@ -1,71 +0,0 @@
import type { NextConfig } from "next";
// Basemap (CartoDB Positron via MapLibre) hosts used by the client.
const MAP_TILE_HOSTS = "https://basemaps.cartocdn.com https://*.basemaps.cartocdn.com";
const nextConfig: NextConfig = {
compress: true,
async headers() {
const securityHeaders = [
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-XSS-Protection", value: "1; mode=block" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
];
const csp = (frameAncestors: string) =>
[
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://va.vercel-scripts.com",
"style-src 'self' 'unsafe-inline'",
`img-src 'self' data: blob: https://logo.clearbit.com ${MAP_TILE_HOSTS}`,
"font-src 'self' data:",
`connect-src 'self' https://va.vercel-scripts.com ${MAP_TILE_HOSTS}`,
"worker-src 'self' blob:",
"child-src 'self' blob:",
`frame-ancestors ${frameAncestors}`,
].join("; ");
return [
{
source: "/embed",
headers: [
...securityHeaders,
{ key: "Content-Security-Policy", value: csp("*") },
],
},
{
source: "/((?!embed).*)",
headers: [
...securityHeaders,
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Content-Security-Policy", value: csp("'none'") },
],
},
{
// Crop-out + national GeoJSON: cache 1 hour.
source: "/data/:path*.geojson",
headers: [
{ key: "Cache-Control", value: "public, max-age=3600, must-revalidate" },
{ key: "Content-Type", value: "application/geo+json" },
],
},
{
// Per-gemeente detail bundles: cache 1 hour + SWR.
source: "/data/:path*.json",
headers: [
{ key: "Cache-Control", value: "public, max-age=3600, stale-while-revalidate=86400" },
],
},
{
source: "/municipalities.json",
headers: [
{ key: "Cache-Control", value: "public, max-age=86400, stale-while-revalidate=3600" },
],
},
];
},
};
export default nextConfig;
-7777
View File
File diff suppressed because it is too large Load Diff
-33
View File
@@ -1,33 +0,0 @@
{
"name": "laadpalenviewer",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@deck.gl/core": "^9.2.6",
"@deck.gl/layers": "^9.2.6",
"@deck.gl/mapbox": "^9.2.6",
"@vercel/analytics": "^1.5.0",
"lucide-react": "^0.447.0",
"maplibre-gl": "^4.7.1",
"next": "^16.0.7",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-map-gl": "^7.1.9"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16.0.7",
"tailwindcss": "^4",
"typescript": "^5"
}
}
-5
View File
@@ -1,5 +0,0 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;
File diff suppressed because one or more lines are too long
@@ -1,153 +0,0 @@
{
"metrics": [
{
"key": "chargers_per_1000_inw",
"label": "Laadpunten per 1.000 inwoners",
"unit": "",
"decimals": 1,
"category": "Aanbod",
"desc": "Aantal OCPI-laadlocaties (NDW) gedeeld door inwoners (CBS) × 1.000. Maat voor dekking."
},
{
"key": "chargers_per_1000_auto",
"label": "Laadpunten per 1.000 auto's",
"unit": "",
"decimals": 1,
"category": "Aanbod",
"desc": "Laadlocaties per 1.000 personenauto's (CBS autobezit). Dekking t.o.v. het wagenpark."
},
{
"key": "chargers_total",
"label": "Laadpunten totaal",
"unit": "",
"decimals": 0,
"category": "Aanbod",
"desc": "Totaal aantal OCPI-laadlocaties (personen + vracht) in de gemeente."
},
{
"key": "power_per_1000_inw_kw",
"label": "Vermogen per 1.000 inw.",
"unit": "kW",
"decimals": 0,
"category": "Aanbod",
"desc": "Som van het max. connectorvermogen per 1.000 inwoners (personen + vracht). Vermogen afgeleid uit spanning × stroomsterkte waar NDW het niet rapporteert."
},
{
"key": "chargers_freight",
"label": "Truck-laadlocaties",
"unit": "",
"decimals": 0,
"category": "Logistiek",
"desc": "Locaties voor truckladen: dedicated voorzieningen (truck-operator, 'truck' in naam, MCS, logistiek depot) plus truck-capable snelladers (≥350 kW DC)."
},
{
"key": "freight_dedicated",
"label": "Dedicated truck-locaties",
"unit": "",
"decimals": 0,
"category": "Logistiek",
"desc": "Locaties met een expliciet trucksignaal: exploitant (Milence/WattHub), 'truck' in de naam, MCS-aansluiting, logistiek depot met ≥150 kW DC, of gecureerde hub. Exclusief locaties die alleen op vermogen kwalificeren."
},
{
"key": "freight_power_kw",
"label": "Truck-laadvermogen",
"unit": "kW",
"decimals": 0,
"category": "Logistiek",
"desc": "Som van het max. connectorvermogen van truck-laadlocaties in de gemeente. Indicatie van logistieke laadcapaciteit (bays per site niet meegenomen)."
},
{
"key": "avg_occupancy",
"label": "Gem. bezetting (snapshot)",
"unit": "%",
"decimals": 1,
"category": "Gebruik",
"desc": "Gemiddeld aandeel connectoren dat 'laadt' over de geregistreerde snapshot-uren."
},
{
"key": "price_kwh_median",
"label": "Mediaan tarief (€/kWh)",
"unit": "€/kWh",
"decimals": 3,
"category": "Prijs",
"desc": "Mediaan van het actuele energietarief (€/kWh) uit de OCPI-tarieven (NDW) over laadlocaties met een gepubliceerde prijs. ±50% van de connectoren publiceert geen tarief; momentopname uit de laatste data-update."
},
{
"key": "demand_per_1000_inw",
"label": "Verwacht aanbod (peer-model)",
"unit": "/1.000 inw",
"decimals": 1,
"category": "Vraag",
"desc": "Door een random-forest voorspeld aantal laadpunten o.b.v. demografie, per 1.000 inwoners. Peer-benchmark van het aanbod, geen gemeten vraag."
},
{
"key": "supply_gap",
"label": "Afwijking t.o.v. peers",
"unit": "laadpunten",
"decimals": 0,
"category": "Vraag",
"desc": "Werkelijk − verwacht (peer-model) aantal laadpunten. Negatief = minder aanbod dan demografisch vergelijkbare gemeenten. Gemodelleerd; NDW-dekkingsgaten (bijv. Amsterdam) kleuren dit beeld."
},
{
"key": "siting_priority",
"label": "Plaatsingsprioriteit (0-100)",
"unit": "",
"decimals": 0,
"category": "Siting",
"desc": "Prioriteit voor bijplaatsen: combineert relatief + absoluut tekort en huidige bezetting. Hoger = meer behoefte."
},
{
"key": "load_per_1000_inw_kw",
"label": "Gesch. piekbelasting /1.000 inw",
"unit": "kW",
"decimals": 1,
"category": "Congestie",
"desc": "Gemodelleerde potentiële piek ((personen-EVSE's × ~11 kW + truck-locaties × ~150 kW) × 30%) per 1.000 inwoners. Vermogens aangenomen."
},
{
"key": "congestion_index",
"label": "Congestie-index (relatief)",
"unit": "",
"decimals": 0,
"category": "Congestie",
"desc": "Relatieve percentielrang (0-100) van de piekbelasting per inwoner. NB: geen DSO-capaciteit ingelezen."
},
{
"key": "autos_per_huishouden",
"label": "Auto's per huishouden",
"unit": "",
"decimals": 2,
"category": "Demografie",
"desc": "CBS: personenauto's per huishouden — driver van laadbehoefte."
},
{
"key": "inkomen_per_inwoner",
"label": "Gem. inkomen per inwoner",
"unit": "×€1.000",
"decimals": 1,
"category": "Demografie",
"desc": "CBS gemiddeld inkomen per inwoner (×€1.000)."
},
{
"key": "stedelijkheid",
"label": "Stedelijkheid (1=zeer sterk)",
"unit": "",
"decimals": 0,
"category": "Demografie",
"desc": "CBS stedelijkheidsklasse 1 (zeer sterk stedelijk) t/m 5 (niet stedelijk)."
}
],
"model": {
"r2_oof": 0.722,
"mae_oof": 57.0,
"feature_importance": {
"inwoners": 0.449,
"huishoudens": 0.25,
"autos_totaal": 0.23,
"autos_per_huishouden": 0.002,
"inkomen_per_inwoner": 0.009,
"stedelijkheid": 0.0,
"adresdichtheid": 0.06
}
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More