"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) => 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(null); const [deckOverlay, setDeckOverlay] = useState(null); const [hovered, setHovered] = useState(null); const [areaHover, setAreaHover] = useState(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") f.push(feat); else p.push(feat); } return { passenger: p, freight: f }; }, [chargeFeatures, filters.minPowerKw]); const handleHover = useCallback((info: PickingInfo) => { setHovered(info.object ?? null); }, []); const handleClick = useCallback( (info: PickingInfo) => { 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 }) => { 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 } | null; if (o?.properties && onAreaSelect) onAreaSelect(o.properties); }, onHover: (info: PickingInfo) => { const o = info.object as { properties?: Record } | 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({ ...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({ ...scatterCommon, id: "freight", data: freight, radiusMinPixels: 5, radiusMaxPixels: 16, getRadius: (d) => d.properties.locationId === selectedLocationId ? 16 : d.properties.isMegawatt ? 11 : 8, getFillColor: (d) => (priceActive ? priceColor(d.properties.priceKwh) : 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], 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 (
{hovered && (
{hovered.properties.name}
{hovered.properties.city && (
{hovered.properties.city}
)} {hovered.properties.operatorName && (
{hovered.properties.operatorName}
)}
{hovered.properties.layer === "freight" ? "Vracht" : "Personenauto"} {hovered.properties.maxPowerKw > 0 && {hovered.properties.maxPowerKw} kW}
{typeof hovered.properties.priceKwh === "number" && (
Tarief: {fmtPrice(hovered.properties.priceKwh)} / kWh
)}
Klik voor details
)} {/* Choropleth area hover */} {choroActive && areaHover && (
{areaHover.gemeente}
{metricMeta?.label}:{" "} {areaHover.value === null ? "geen data" : `${fmt(areaHover.value)}${metricMeta?.unit ? " " + metricMeta.unit : ""}`}
)}
{/* Choropleth legend */} {choroActive && metricDomain && (
{metricMeta?.label}
{fmt(metricDomain[0])} {fmt(metricDomain[1])}{metricMeta?.unit ? ` ${metricMeta.unit}` : ""}
geen data
)} {/* Price legend */} {priceActive && priceDomain && (
Tarief (€/kWh)
{fmtPrice(priceDomain[0])} {fmtPrice(priceDomain[1])}
geen tarief
)} {/* Marker legend */} {!choroActive && !priceActive && (
Personenauto (status)
Beschikbaar
Bezet (laden)
Niet beschikbaar
Onbekend
Logistiek / vracht
Vracht-laadpunt
Megawatt charging
)}
); }