Initial commit: Laadpalenviewer

Static-generation EV charging map for the Netherlands with two layers
(passenger / logistics-freight), per-municipality crop-outs, and
gemeente + province boundaries from PDOK/CBS.

- data-pipeline/ (Node/TS): NDW OCPI download + classify (freight >=350kW /
  MCS / megawatt / Milence,WattHub) + external sources (curated, OCM, EAFO)
  + PDOK CBS boundaries -> static GeoJSON/JSON.
- webapp/ (Next.js 16 + React 19 + deck.gl + MapLibre): national view loads
  all points without details; selecting a gemeente eagerly loads its detail
  bundle (OCPI EVSE/connector/tariff + status) for instant marker clicks.
  Passenger colored by OCPI status (fleetsim-style), freight amber/megawatt.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Robbert Janssen
2026-06-02 15:26:56 +02:00
co-authored by Claude Opus 4.8
commit ab9ed8abb8
733 changed files with 18413 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
/node_modules
/.next
/out
/build
next-env.d.ts
.DS_Store
*.tsbuildinfo
.vercel
.env*.local
+255
View File
@@ -0,0 +1,255 @@
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
@@ -0,0 +1,72 @@
"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
@@ -0,0 +1,34 @@
@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
@@ -0,0 +1,37 @@
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>
);
}
+270
View File
@@ -0,0 +1,270 @@
"use client";
import { useState, useEffect, useMemo } 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 AboutModal from "@/components/AboutModal";
import ShareModal from "@/components/ShareModal";
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 [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const isNational = selectedMunicipality === "nederland";
// 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]);
// 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] = await Promise.all([
fetch(`/data/gemeenten/${selectedMunicipality}.geojson`),
fetch(`/data/gemeenten/${selectedMunicipality}.details.json`),
]);
const crop = (await cropRes.json()) as CropoutData;
const bundle = (await detRes.json()) as DetailBundle;
if (cancelled) return;
const charges = crop.features.filter((f) => f.properties.type === "charge") as ChargeFeature[];
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);
}
};
load()
.catch((e) => console.error("data load failed", e))
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [selectedMunicipality]);
const { passengerCount, freightCount } = useMemo(() => {
let p = 0;
let f = 0;
for (const feat of chargeFeatures) {
if (feat.properties.layer === "freight") f++;
else p++;
}
return { passengerCount: p, freightCount: f };
}, [chargeFeatures]);
const selectedDetail = selected ? details[selected.properties.locationId] ?? null : null;
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">
<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={() => 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} />
<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={filters}
selectedLocationId={selected?.properties.locationId ?? null}
onSelect={setSelected}
/>
<LocationDetailPanel
selected={selected}
detail={selectedDetail}
loading={false}
onClose={() => setSelected(null)}
/>
{/* 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)} />
<ShareModal
isOpen={showShare}
onClose={() => setShowShare(false)}
municipality={selectedMunicipality}
municipalityName={municipalities.find((m) => m.slug === selectedMunicipality)?.name || selectedMunicipality}
/>
</div>
);
}
+66
View File
@@ -0,0 +1,66 @@
"use client";
import { X } from "lucide-react";
interface Props {
isOpen: boolean;
onClose: () => void;
}
export default function AboutModal({ isOpen, onClose }: 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-lg w-full max-h-[85vh] overflow-y-auto"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between p-4 border-b">
<h2 className="text-lg font-semibold">Over Laadpalenviewer</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 text-gray-700">
<p>
Laadpalenviewer toont laadpunten in Nederland op een interactieve kaart, opgesplitst in twee lagen:
<strong> personenauto&apos;s</strong> en <strong>logistiek/vracht</strong> (zware voertuigen en
megawatt charging).
</p>
<div>
<h3 className="font-medium text-gray-900 mb-1">Databronnen</h3>
<ul className="list-disc list-inside space-y-1">
<li>
<strong>NDW DOT-NL (OCPI)</strong> — alle publiek toegankelijke laadpunten in Nederland.
Open data via opendata.ndw.nu.
</li>
<li>
<strong>Vracht/logistiek</strong> — classificatie van NDW-data op zeer hoog vermogen
(DC ≥ 350 kW), megawatt/MCS-standaard en exploitant, aangevuld met bekende truckhubs
(Milence, WattHub) en Open Charge Map. Reguliere snelladers (150–350 kW) voor
personenauto&apos;s blijven in de personenauto-laag.
</li>
<li>
<strong>Gemeente- en provinciegrenzen</strong> — PDOK CBS Gebiedsindelingen (WFS).
</li>
<li>
<strong>Adres zoeken</strong> — PDOK Locatieserver.
</li>
</ul>
</div>
<div>
<h3 className="font-medium text-gray-900 mb-1">Detailniveau</h3>
<p>
Op landelijk niveau worden alle laadpunten getoond zonder details (snel). Bij het kiezen van
een gemeente worden alle details (laadpunten, connectoren, tarieven) direct geladen, zodat
klikken op een marker meteen volledige informatie toont.
</p>
</div>
<p className="text-xs text-gray-500">
Classificatie en deduplicatie zijn heuristisch; controleer voor operationeel gebruik altijd de bron.
</p>
</div>
</div>
</div>
);
}
+388
View File
@@ -0,0 +1,388 @@
'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>
);
}
+90
View File
@@ -0,0 +1,90 @@
"use client";
import type { Filters } from "@/types/charging";
import { LEGEND } from "@/lib/colors";
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">
<h3 className="text-sm font-semibold text-gray-900">Kaartlagen</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>
<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">Min. vermogen</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>
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
"use client";
import { X, ExternalLink, Clock, Zap, MapPin, Building2, Truck } from "lucide-react";
import type { ChargeFeature, EnrichedLocation } from "@/types/charging";
import { formatConnectorStandard, formatPowerType, statusColorClass, statusLabel } from "@/lib/connectorLabels";
interface Props {
selected: ChargeFeature | null;
detail: EnrichedLocation | null;
loading: boolean;
onClose: () => void;
onJumpToGemeente?: () => void;
}
export default function LocationDetailPanel({ selected, detail, loading, onClose, onJumpToGemeente }: Props) {
if (!selected) return null;
const p = selected.properties;
const isFreight = p.layer === "freight";
return (
<div 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 ? "Vracht" : "Personenauto"}
</span>
{p.isMegawatt && (
<span className="px-1.5 py-0.5 rounded text-xs text-white bg-orange-600">Megawatt</span>
)}
</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>
{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>
{c.max_electric_power ? (
<span className="font-medium">{(c.max_electric_power / 1000).toFixed(1)} kW</span>
) : null}
</div>
{c.tariffs.length > 0 && c.tariffs[0].elements?.[0]?.price_components?.[0] && (
<div className="text-gray-500">
Tarief: {c.tariffs[0].elements[0].price_components[0].price}{" "}
{c.tariffs[0].currency} / {c.tariffs[0].elements[0].price_components[0].type.toLowerCase()}
</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>
);
}
+270
View File
@@ -0,0 +1,270 @@
"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 { statusColor, freightColor, BOUNDARY_LINE, LEGEND, type RGBA } from "@/lib/colors";
interface MapDeckProps {
chargeFeatures: ChargeFeature[];
boundaryFeatures: BoundaryFeature[];
bounds: [number, number, number, number] | null;
filters: Filters;
selectedLocationId: string | null;
onSelect: (feature: ChargeFeature | null) => void;
}
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,
}: MapDeckProps) {
const mapRef = useRef<MapRef>(null);
const [deckOverlay, setDeckOverlay] = useState<MapboxOverlay | null>(null);
const [hovered, setHovered] = useState<ChargeFeature | null>(null);
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") f.push(feat);
else p.push(feat);
}
return { passenger: p, freight: f };
}, [chargeFeatures, filters.minPowerKw]);
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[] = [];
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) => statusColor(d.properties.status),
updateTriggers: { getRadius: [selectedLocationId], getFillColor: [] },
}),
);
}
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 : 8,
getFillColor: (d) => freightColor(d.properties.isMegawatt),
getLineColor: (d) =>
d.properties.isMegawatt ? ([124, 45, 18, 255] as RGBA) : ([255, 255, 255, 230] as RGBA),
getLineWidth: (d) => (d.properties.isMegawatt ? 2 : 1),
updateTriggers: { getRadius: [selectedLocationId] },
}),
);
}
return result;
}, [
passenger,
freight,
boundaryFeatures,
filters.showPassenger,
filters.showFreight,
filters.showBoundary,
selectedLocationId,
handleHover,
handleClick,
]);
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)}</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
: LEGEND.freight
: LEGEND[
(
{
AVAILABLE: "available",
CHARGING: "charging",
UNAVAILABLE: "unavailable",
UNKNOWN: "unknown",
} as const
)[hovered.properties.status]
],
}}
>
{hovered.properties.layer === "freight" ? "Vracht" : "Personenauto"}
</span>
{hovered.properties.maxPowerKw > 0 && <span>{hovered.properties.maxPowerKw} kW</span>}
</div>
<div className="text-xs text-blue-600 mt-1">Klik voor details</div>
</div>
</Popup>
)}
</Map>
{/* Legend */}
<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">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>Vracht-laadpunt</span>
</div>
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full" style={{ background: LEGEND.freightMegawatt }} />
<span>Megawatt charging</span>
</div>
</div>
</div>
</div>
);
}
+312
View File
@@ -0,0 +1,312 @@
'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
@@ -0,0 +1,82 @@
"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>
);
}
+98
View File
@@ -0,0 +1,98 @@
"use client";
import { useMemo } from "react";
import type { ChargeFeature } from "@/types/charging";
import { LEGEND } from "@/lib/colors";
interface StatsPanelProps {
gemeente: string;
chargeFeatures: ChargeFeature[];
}
export default function StatsPanel({ gemeente, chargeFeatures }: StatsPanelProps) {
const stats = useMemo(() => {
let passenger = 0;
let freight = 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.isMegawatt) megawatt++;
} else {
passenger++;
}
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, 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">Logistiek / vracht</div>
</div>
</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">Status (OCPI-momentopname)</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>
);
}
+12
View File
@@ -0,0 +1,12 @@
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;
+44
View File
@@ -0,0 +1,44 @@
// 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.
export const FREIGHT: RGBA = [245, 158, 11, 235]; // amber-500
export const FREIGHT_MEGAWATT: RGBA = [234, 88, 12, 245]; // orange-600
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): RGBA {
return isMegawatt ? FREIGHT_MEGAWATT : FREIGHT;
}
// Hex equivalents for legend / UI swatches.
export const LEGEND = {
available: "#22c55e",
charging: "#3b82f6",
unavailable: "#ef4444",
unknown: "#6b7280",
freight: "#f59e0b",
freightMegawatt: "#ea580c",
boundary: "#4f46e5",
};
+62
View File
@@ -0,0 +1,62 @@
// 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;
}
+71
View File
@@ -0,0 +1,71 @@
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
@@ -0,0 +1,33 @@
{
"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
@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;
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
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
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
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