Restore BAG-gebied integration
Re-applies the previously stashed BAG feature on top of the API/MCP work:
PDOK BAG address/area lookup with map drawing (maplibre-gl + terra-draw),
counting verblijfsobjecten per gebruiksdoel and applying them as model
function counts/BVO via handleApplyBagPlan.
New API routes: /api/bag/query, /api/pdok/{lookup,reverse,suggest},
/api/nwb/streets. New BAG UI components, contexts, and helper libs
(bag-mapping, osm, wkt). Adds maplibre-gl, terra-draw, @turf/turf deps.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
e4bc1cfc2f
commit
bf47f0fe5b
Generated
+2559
-3
File diff suppressed because it is too large
Load Diff
+5
-1
@@ -9,16 +9,20 @@
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@turf/turf": "^7.3.5",
|
||||
"@vercel/analytics": "^1.6.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"maplibre-gl": "^5.23.0",
|
||||
"next": "16.1.6",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"recharts": "^3.7.0",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"terra-draw": "^1.28.8",
|
||||
"terra-draw-maplibre-gl-adapter": "^1.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { Feature, FeatureCollection, MultiPolygon, Point, Polygon, Position } from 'geojson';
|
||||
import { bbox as turfBbox, booleanPointInPolygon } from '@turf/turf';
|
||||
import {
|
||||
BAG_GEBRUIKSDOELEN,
|
||||
type BagBucket,
|
||||
type BagGebruiksdoel,
|
||||
type BagQueryResult,
|
||||
type BagVboProperties,
|
||||
} from '@/lib/bag-types';
|
||||
import { fetchOsmPois, findNearestOsm, isHorecaPoi, isShopPoi } from '@/lib/osm';
|
||||
|
||||
const WFS_URL = 'https://service.pdok.nl/lv/bag/wfs/v2_0';
|
||||
const PAGE_SIZE = 1000;
|
||||
const MAX_PAGES = 30;
|
||||
const MAX_BBOX_DEG2 = 0.02;
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const maxDuration = 60;
|
||||
|
||||
interface WfsFeature {
|
||||
geometry?: { type: string; coordinates: Position | Position[] | Position[][] };
|
||||
properties?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function normalizeGebruiksdoelen(raw: unknown): string[] {
|
||||
if (Array.isArray(raw)) return raw.map((v) => String(v).trim().toLowerCase()).filter(Boolean);
|
||||
if (typeof raw === 'string') return raw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
|
||||
return [];
|
||||
}
|
||||
|
||||
function extractPoint(feat: WfsFeature): [number, number] | null {
|
||||
const g = feat.geometry;
|
||||
if (!g) return null;
|
||||
if (g.type === 'Point' && Array.isArray(g.coordinates) && typeof g.coordinates[0] === 'number') {
|
||||
return [g.coordinates[0] as number, g.coordinates[1] as number];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
let body: { polygon?: Feature<Polygon | MultiPolygon> };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
|
||||
}
|
||||
|
||||
const polygon = body.polygon;
|
||||
if (
|
||||
!polygon ||
|
||||
polygon.type !== 'Feature' ||
|
||||
!polygon.geometry ||
|
||||
(polygon.geometry.type !== 'Polygon' && polygon.geometry.type !== 'MultiPolygon')
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Body must be { polygon: Feature<Polygon | MultiPolygon> }' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const [minX, minY, maxX, maxY] = turfBbox(polygon);
|
||||
const bboxDeg2 = (maxX - minX) * (maxY - minY);
|
||||
if (bboxDeg2 > MAX_BBOX_DEG2) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Selected area is too large — teken een kleiner gebied (< ~20 km²).' },
|
||||
{ status: 413 }
|
||||
);
|
||||
}
|
||||
|
||||
const allFeatures: WfsFeature[] = [];
|
||||
let truncated = false;
|
||||
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
const params = new URLSearchParams({
|
||||
service: 'WFS',
|
||||
version: '2.0.0',
|
||||
request: 'GetFeature',
|
||||
typeNames: 'bag:verblijfsobject',
|
||||
outputFormat: 'application/json',
|
||||
srsName: 'EPSG:4326',
|
||||
bbox: `${minY},${minX},${maxY},${maxX},EPSG:4326`,
|
||||
count: String(PAGE_SIZE),
|
||||
startIndex: String(page * PAGE_SIZE),
|
||||
});
|
||||
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await fetch(`${WFS_URL}?${params.toString()}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: `PDOK BAG WFS unreachable: ${(err as Error).message}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text().catch(() => '');
|
||||
return NextResponse.json(
|
||||
{ error: `PDOK BAG WFS returned ${resp.status}`, detail: text.slice(0, 500) },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
const fc = (await resp.json()) as { features?: WfsFeature[] };
|
||||
const feats = fc.features ?? [];
|
||||
allFeatures.push(...feats);
|
||||
|
||||
if (feats.length === 0) break;
|
||||
if (page === MAX_PAGES - 1) truncated = true;
|
||||
}
|
||||
|
||||
const subPolygons: Feature<Polygon>[] =
|
||||
polygon.geometry.type === 'Polygon'
|
||||
? [polygon as Feature<Polygon>]
|
||||
: polygon.geometry.coordinates.map((coords) => ({
|
||||
type: 'Feature',
|
||||
geometry: { type: 'Polygon', coordinates: coords },
|
||||
properties: {},
|
||||
}));
|
||||
|
||||
const inPolygon: WfsFeature[] = [];
|
||||
for (const feat of allFeatures) {
|
||||
const pt = extractPoint(feat);
|
||||
if (!pt) continue;
|
||||
for (const sub of subPolygons) {
|
||||
if (booleanPointInPolygon(pt, sub)) {
|
||||
inPolygon.push(feat);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fire-and-forget OSM fetch in parallel; we'll await later.
|
||||
const osmPromise = fetchOsmPois([minX, minY, maxX, maxY]).catch((err) => {
|
||||
console.error('[bag/query] OSM fetch failed:', (err as Error).message);
|
||||
return [];
|
||||
});
|
||||
|
||||
const buckets: Partial<Record<BagGebruiksdoel, BagBucket>> = {};
|
||||
let multiUseCount = 0;
|
||||
const vboFeatures: Feature<Point, BagVboProperties>[] = [];
|
||||
let totalCounted = 0;
|
||||
|
||||
for (const feat of inPolygon) {
|
||||
const props = feat.properties ?? {};
|
||||
const statusRaw = typeof props.status === 'string' ? props.status.toLowerCase() : '';
|
||||
if (statusRaw.includes('ingetrokken') || statusRaw.includes('niet gerealiseerd')) continue;
|
||||
|
||||
const doelen = normalizeGebruiksdoelen(props.gebruiksdoel);
|
||||
if (doelen.length === 0) continue;
|
||||
if (doelen.length > 1) multiUseCount += 1;
|
||||
|
||||
const primary = doelen[0];
|
||||
if (!BAG_GEBRUIKSDOELEN.includes(primary as BagGebruiksdoel)) continue;
|
||||
|
||||
const key = primary as BagGebruiksdoel;
|
||||
const oppervlakte = Number(props.oppervlakte ?? 0) || 0;
|
||||
if (!buckets[key]) {
|
||||
buckets[key] = { gebruiksdoel: key, count: 0, totalOppervlakte: 0, oppervlakten: [] };
|
||||
}
|
||||
const bucket = buckets[key]!;
|
||||
bucket.count += 1;
|
||||
bucket.totalOppervlakte += oppervlakte;
|
||||
bucket.oppervlakten.push(oppervlakte);
|
||||
totalCounted += 1;
|
||||
|
||||
const pt = extractPoint(feat);
|
||||
if (pt) {
|
||||
vboFeatures.push({
|
||||
type: 'Feature',
|
||||
geometry: { type: 'Point', coordinates: pt },
|
||||
properties: {
|
||||
id: typeof props.identificatie === 'string' ? props.identificatie : undefined,
|
||||
gebruiksdoel: key,
|
||||
oppervlakte,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const osmPois = await osmPromise;
|
||||
if (osmPois.length > 0) {
|
||||
for (const f of vboFeatures) {
|
||||
const g = f.properties.gebruiksdoel;
|
||||
const coords = f.geometry.coordinates as [number, number];
|
||||
let nearest = null;
|
||||
if (g === 'winkelfunctie') {
|
||||
nearest = findNearestOsm(coords, osmPois, 25, isShopPoi);
|
||||
} else if (g === 'bijeenkomstfunctie') {
|
||||
nearest = findNearestOsm(coords, osmPois, 25, isHorecaPoi);
|
||||
}
|
||||
if (nearest) {
|
||||
f.properties.osm = {
|
||||
shop: nearest.shop,
|
||||
amenity: nearest.amenity,
|
||||
brand: nearest.brand,
|
||||
name: nearest.name,
|
||||
cuisine: nearest.cuisine,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const featureCollection: FeatureCollection<Point, BagVboProperties> = {
|
||||
type: 'FeatureCollection',
|
||||
features: vboFeatures,
|
||||
};
|
||||
|
||||
const result: BagQueryResult = {
|
||||
totalVerblijfsobjecten: totalCounted,
|
||||
buckets,
|
||||
polygon,
|
||||
features: featureCollection,
|
||||
queriedAt: new Date().toISOString(),
|
||||
truncated,
|
||||
multiUseCount,
|
||||
};
|
||||
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
const WFS_URL = 'https://service.pdok.nl/rws/nwbwegen/wfs/v1_0';
|
||||
const PAGE_SIZE = 5000;
|
||||
const MAX_BBOX_DEG2 = 0.05;
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const maxDuration = 30;
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const url = new URL(req.url);
|
||||
const minX = parseFloat(url.searchParams.get('minX') ?? '');
|
||||
const minY = parseFloat(url.searchParams.get('minY') ?? '');
|
||||
const maxX = parseFloat(url.searchParams.get('maxX') ?? '');
|
||||
const maxY = parseFloat(url.searchParams.get('maxY') ?? '');
|
||||
|
||||
if ([minX, minY, maxX, maxY].some((v) => Number.isNaN(v))) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Query params minX, minY, maxX, maxY (EPSG:4326) are required.' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (minX >= maxX || minY >= maxY) {
|
||||
return NextResponse.json({ error: 'Invalid bbox: min must be < max.' }, { status: 400 });
|
||||
}
|
||||
if ((maxX - minX) * (maxY - minY) > MAX_BBOX_DEG2) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Bbox too large. Zoom in closer to load streets.' },
|
||||
{ status: 413 }
|
||||
);
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
service: 'WFS',
|
||||
version: '2.0.0',
|
||||
request: 'GetFeature',
|
||||
typeNames: 'nwbwegen:wegvakken',
|
||||
outputFormat: 'application/json',
|
||||
srsName: 'EPSG:4326',
|
||||
bbox: `${minY},${minX},${maxY},${maxX},EPSG:4326`,
|
||||
count: String(PAGE_SIZE),
|
||||
});
|
||||
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await fetch(`${WFS_URL}?${params.toString()}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: `PDOK NWB unreachable: ${(err as Error).message}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text().catch(() => '');
|
||||
return NextResponse.json(
|
||||
{ error: `PDOK NWB returned ${resp.status}`, detail: text.slice(0, 500) },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
const fc = await resp.json();
|
||||
return NextResponse.json(fc, {
|
||||
headers: {
|
||||
'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { wktToGeoJSON } from '@/lib/wkt';
|
||||
import type { LineString, MultiLineString, MultiPolygon, Point, Polygon } from 'geojson';
|
||||
|
||||
const LOOKUP_URL = 'https://api.pdok.nl/bzk/locatieserver/search/v3_1/lookup';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export interface LocatieserverLookupResult {
|
||||
id: string;
|
||||
weergavenaam: string;
|
||||
type: string;
|
||||
centroid: Point | null;
|
||||
geometry: LineString | MultiLineString | Polygon | MultiPolygon | null;
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const url = new URL(req.url);
|
||||
const id = url.searchParams.get('id')?.trim();
|
||||
if (!id) return NextResponse.json({ error: 'id required' }, { status: 400 });
|
||||
|
||||
const params = new URLSearchParams({ id, fl: '*' });
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await fetch(`${LOOKUP_URL}?${params.toString()}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: `PDOK Locatieserver unreachable: ${(err as Error).message}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
if (!resp.ok) {
|
||||
return NextResponse.json({ error: `PDOK returned ${resp.status}` }, { status: 502 });
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as {
|
||||
response?: {
|
||||
docs?: Array<{
|
||||
id: string;
|
||||
weergavenaam: string;
|
||||
type: string;
|
||||
centroide_ll?: string;
|
||||
geometrie_ll?: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
const doc = data.response?.docs?.[0];
|
||||
if (!doc) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const centroidWkt = doc.centroide_ll ? wktToGeoJSON(doc.centroide_ll) : null;
|
||||
const geomWkt = doc.geometrie_ll ? wktToGeoJSON(doc.geometrie_ll) : null;
|
||||
|
||||
const geometry =
|
||||
geomWkt?.type === 'Polygon' ||
|
||||
geomWkt?.type === 'MultiPolygon' ||
|
||||
geomWkt?.type === 'LineString' ||
|
||||
geomWkt?.type === 'MultiLineString'
|
||||
? geomWkt
|
||||
: null;
|
||||
|
||||
const result: LocatieserverLookupResult = {
|
||||
id: doc.id,
|
||||
weergavenaam: doc.weergavenaam,
|
||||
type: doc.type,
|
||||
centroid: centroidWkt?.type === 'Point' ? centroidWkt : null,
|
||||
geometry,
|
||||
};
|
||||
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
const REVERSE_URL = 'https://api.pdok.nl/bzk/locatieserver/search/v3_1/reverse';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export interface PdokReverseResult {
|
||||
weergavenaam: string | null;
|
||||
straatnaam: string | null;
|
||||
huisnummer: number | null;
|
||||
huisletter: string | null;
|
||||
huisnummertoevoeging: string | null;
|
||||
postcode: string | null;
|
||||
woonplaats: string | null;
|
||||
distanceMeters: number | null;
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const url = new URL(req.url);
|
||||
const lat = parseFloat(url.searchParams.get('lat') ?? '');
|
||||
const lon = parseFloat(url.searchParams.get('lon') ?? '');
|
||||
if (Number.isNaN(lat) || Number.isNaN(lon)) {
|
||||
return NextResponse.json({ error: 'lat & lon required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
lat: lat.toString(),
|
||||
lon: lon.toString(),
|
||||
rows: '1',
|
||||
type: 'adres',
|
||||
fl: 'weergavenaam,straatnaam,huisnummer,huisletter,huisnummertoevoeging,postcode,woonplaatsnaam,afstand',
|
||||
});
|
||||
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await fetch(`${REVERSE_URL}?${params.toString()}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: `PDOK reverse unreachable: ${(err as Error).message}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
if (!resp.ok) {
|
||||
return NextResponse.json({ error: `PDOK returned ${resp.status}` }, { status: 502 });
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as {
|
||||
response?: {
|
||||
docs?: Array<{
|
||||
weergavenaam?: string;
|
||||
straatnaam?: string;
|
||||
huisnummer?: number;
|
||||
huisletter?: string;
|
||||
huisnummertoevoeging?: string;
|
||||
postcode?: string;
|
||||
woonplaatsnaam?: string;
|
||||
afstand?: number;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
const d = data.response?.docs?.[0];
|
||||
if (!d) return NextResponse.json({ error: 'No address found' }, { status: 404 });
|
||||
|
||||
const result: PdokReverseResult = {
|
||||
weergavenaam: d.weergavenaam ?? null,
|
||||
straatnaam: d.straatnaam ?? null,
|
||||
huisnummer: d.huisnummer ?? null,
|
||||
huisletter: d.huisletter ?? null,
|
||||
huisnummertoevoeging: d.huisnummertoevoeging ?? null,
|
||||
postcode: d.postcode ?? null,
|
||||
woonplaats: d.woonplaatsnaam ?? null,
|
||||
distanceMeters: d.afstand ?? null,
|
||||
};
|
||||
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
const SUGGEST_URL = 'https://api.pdok.nl/bzk/locatieserver/search/v3_1/suggest';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export interface LocatieserverSuggestion {
|
||||
id: string;
|
||||
weergavenaam: string;
|
||||
type: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const url = new URL(req.url);
|
||||
const q = url.searchParams.get('q')?.trim();
|
||||
if (!q) return NextResponse.json({ suggestions: [] });
|
||||
|
||||
const params = new URLSearchParams({
|
||||
q,
|
||||
rows: '8',
|
||||
fq: 'type:(adres OR weg OR woonplaats OR buurt OR wijk)',
|
||||
});
|
||||
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await fetch(`${SUGGEST_URL}?${params.toString()}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: `PDOK Locatieserver unreachable: ${(err as Error).message}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
return NextResponse.json({ error: `PDOK returned ${resp.status}` }, { status: 502 });
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as {
|
||||
response?: { docs?: Array<{ id: string; weergavenaam: string; type: string; score: number }> };
|
||||
};
|
||||
|
||||
const suggestions: LocatieserverSuggestion[] = (data.response?.docs ?? []).map((d) => ({
|
||||
id: d.id,
|
||||
weergavenaam: d.weergavenaam,
|
||||
type: d.type,
|
||||
score: d.score,
|
||||
}));
|
||||
|
||||
return NextResponse.json({ suggestions });
|
||||
}
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import { IBM_Plex_Sans, IBM_Plex_Sans_Condensed, IBM_Plex_Mono } from "next/font/google";
|
||||
import { Analytics } from "@vercel/analytics/next";
|
||||
import { Providers } from "@/lib/providers";
|
||||
import "./globals.css";
|
||||
|
||||
const ibmPlexSans = IBM_Plex_Sans({
|
||||
@@ -37,7 +38,7 @@ export default function RootLayout({
|
||||
className={`${ibmPlexSans.variable} ${ibmPlexSansCondensed.variable} ${ibmPlexMono.variable} antialiased`}
|
||||
style={{ fontFamily: 'var(--font-ibm-plex-sans), sans-serif' }}
|
||||
>
|
||||
{children}
|
||||
<Providers>{children}</Providers>
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+8
-14
@@ -1,28 +1,22 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { useSimulationState, type LayoutType } from '@/lib/use-simulation-state';
|
||||
import { useTutorial } from '@/lib/use-tutorial';
|
||||
import { useApp } from '@/lib/app-context';
|
||||
|
||||
const DmiCockpitLayout = dynamic(() => import('@/components/layouts/DmiCockpitLayout'), { ssr: false });
|
||||
const WebappLayout = dynamic(() => import('@/components/layouts/WebappLayout'), { ssr: false });
|
||||
|
||||
export default function Home() {
|
||||
const [layout, setLayout] = useState<LayoutType>('dmi');
|
||||
const state = useSimulationState();
|
||||
const tutorial = useTutorial();
|
||||
|
||||
// Stop tutorial on layout switch
|
||||
const handleLayoutChange = (newLayout: LayoutType) => {
|
||||
if (tutorial.isActive) tutorial.stop();
|
||||
setLayout(newLayout);
|
||||
};
|
||||
const { simulation, tutorial, layout, setLayout } = useApp();
|
||||
|
||||
return (
|
||||
<>
|
||||
{layout === 'dmi' && <DmiCockpitLayout state={state} layout={layout} onLayoutChange={handleLayoutChange} tutorial={tutorial} />}
|
||||
{layout === 'webapp' && <WebappLayout state={state} layout={layout} onLayoutChange={handleLayoutChange} tutorial={tutorial} />}
|
||||
{layout === 'dmi' && (
|
||||
<DmiCockpitLayout state={simulation} layout={layout} onLayoutChange={setLayout} tutorial={tutorial} />
|
||||
)}
|
||||
{layout === 'webapp' && (
|
||||
<WebappLayout state={simulation} layout={layout} onLayoutChange={setLayout} tutorial={tutorial} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Search, Loader2 } from 'lucide-react';
|
||||
import { DMI, labelMono } from '@/lib/dmi-theme';
|
||||
import type { LocatieserverSuggestion } from '@/app/api/pdok/suggest/route';
|
||||
import type { LocatieserverLookupResult } from '@/app/api/pdok/lookup/route';
|
||||
|
||||
interface Props {
|
||||
onSelect: (lookup: LocatieserverLookupResult) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
weg: 'straat',
|
||||
adres: 'adres',
|
||||
woonplaats: 'plaats',
|
||||
buurt: 'buurt',
|
||||
wijk: 'wijk',
|
||||
};
|
||||
|
||||
export default function BagAddressSearch({ onSelect, disabled }: Props) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [suggestions, setSuggestions] = useState<LocatieserverSuggestion[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selecting, setSelecting] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (query.trim().length < 2) {
|
||||
setSuggestions([]);
|
||||
return;
|
||||
}
|
||||
const t = setTimeout(async () => {
|
||||
if (abortRef.current) abortRef.current.abort();
|
||||
const ctrl = new AbortController();
|
||||
abortRef.current = ctrl;
|
||||
setLoading(true);
|
||||
try {
|
||||
const resp = await fetch(`/api/pdok/suggest?q=${encodeURIComponent(query)}`, {
|
||||
signal: ctrl.signal,
|
||||
});
|
||||
if (!resp.ok) return;
|
||||
const data = (await resp.json()) as { suggestions: LocatieserverSuggestion[] };
|
||||
setSuggestions(data.suggestions);
|
||||
setOpen(true);
|
||||
} catch (err) {
|
||||
if ((err as Error).name !== 'AbortError') console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, 220);
|
||||
return () => clearTimeout(t);
|
||||
}, [query]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: MouseEvent) => {
|
||||
if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
window.addEventListener('mousedown', handler);
|
||||
return () => window.removeEventListener('mousedown', handler);
|
||||
}, []);
|
||||
|
||||
const pick = useCallback(
|
||||
async (s: LocatieserverSuggestion) => {
|
||||
setSelecting(true);
|
||||
setOpen(false);
|
||||
setQuery(s.weergavenaam);
|
||||
try {
|
||||
const resp = await fetch(`/api/pdok/lookup?id=${encodeURIComponent(s.id)}`);
|
||||
if (!resp.ok) return;
|
||||
const result = (await resp.json()) as LocatieserverLookupResult;
|
||||
onSelect(result);
|
||||
} finally {
|
||||
setSelecting(false);
|
||||
}
|
||||
},
|
||||
[onSelect]
|
||||
);
|
||||
|
||||
return (
|
||||
<div ref={rootRef} style={{ position: 'relative', width: '100%' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
padding: '7px 12px',
|
||||
backgroundColor: DMI.white,
|
||||
border: `1px solid ${DMI.blueTint2}`,
|
||||
borderRadius: 6,
|
||||
}}
|
||||
>
|
||||
{loading || selecting ? (
|
||||
<Loader2 size={14} className="animate-spin" style={{ color: DMI.darkGray }} />
|
||||
) : (
|
||||
<Search size={14} style={{ color: DMI.darkGray }} />
|
||||
)}
|
||||
<input
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onFocus={() => suggestions.length > 0 && setOpen(true)}
|
||||
placeholder="Zoek adres of straat…"
|
||||
disabled={disabled}
|
||||
style={{
|
||||
flex: 1,
|
||||
border: 'none',
|
||||
outline: 'none',
|
||||
background: 'transparent',
|
||||
fontSize: 13,
|
||||
fontFamily: 'inherit',
|
||||
color: DMI.darkBlue,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{open && suggestions.length > 0 && (
|
||||
<ul
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '100%',
|
||||
left: 0,
|
||||
right: 0,
|
||||
marginTop: 4,
|
||||
backgroundColor: DMI.white,
|
||||
border: `1px solid ${DMI.blueTint2}`,
|
||||
borderRadius: 6,
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
|
||||
listStyle: 'none',
|
||||
padding: 0,
|
||||
maxHeight: 280,
|
||||
overflowY: 'auto',
|
||||
zIndex: 30,
|
||||
}}
|
||||
>
|
||||
{suggestions.map((s) => (
|
||||
<li key={s.id}>
|
||||
<button
|
||||
onClick={() => pick(s)}
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '8px 12px',
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
borderBottom: `1px solid ${DMI.blueTint2}`,
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
fontFamily: 'inherit',
|
||||
fontSize: 13,
|
||||
color: DMI.darkBlue,
|
||||
}}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
...labelMono,
|
||||
fontSize: 9,
|
||||
backgroundColor: DMI.blueTint2,
|
||||
color: DMI.darkBlue,
|
||||
padding: '2px 6px',
|
||||
borderRadius: 3,
|
||||
minWidth: 48,
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{TYPE_LABELS[s.type] ?? s.type}
|
||||
</span>
|
||||
<span>{s.weergavenaam}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { useBag } from '@/lib/bag-context';
|
||||
import { BAG_ICONS } from '@/lib/bag-icons';
|
||||
import { classifyHoreca, classifyWinkel } from '@/lib/bag-mapping';
|
||||
import { DMI, heading, bodyText, labelMono } from '@/lib/dmi-theme';
|
||||
import { FUNCTIONS } from '@/lib/model-data';
|
||||
import type { BagVboProperties } from '@/lib/bag-types';
|
||||
|
||||
const FUNC_NAME: Record<string, string> = Object.fromEntries(
|
||||
FUNCTIONS.map((f) => [f.id, f.name])
|
||||
);
|
||||
|
||||
interface Row {
|
||||
vboId: string;
|
||||
gebruiksdoel: 'winkelfunctie' | 'bijeenkomstfunctie';
|
||||
oppervlakte: number;
|
||||
funcId: string;
|
||||
osm?: BagVboProperties['osm'];
|
||||
}
|
||||
|
||||
export default function BagOsmDetails() {
|
||||
const { queryResult } = useBag();
|
||||
|
||||
const rows = useMemo<Row[]>(() => {
|
||||
if (!queryResult) return [];
|
||||
const out: Row[] = [];
|
||||
queryResult.features.features.forEach((f, idx) => {
|
||||
const g = f.properties.gebruiksdoel;
|
||||
if (g !== 'winkelfunctie' && g !== 'bijeenkomstfunctie') return;
|
||||
const funcId =
|
||||
g === 'winkelfunctie' ? classifyWinkel(f.properties) : classifyHoreca(f.properties);
|
||||
out.push({
|
||||
vboId: f.properties.id ?? `idx-${idx}`,
|
||||
gebruiksdoel: g,
|
||||
oppervlakte: f.properties.oppervlakte,
|
||||
funcId,
|
||||
osm: f.properties.osm,
|
||||
});
|
||||
});
|
||||
return out.sort((a, b) => {
|
||||
if (a.funcId !== b.funcId) return a.funcId.localeCompare(b.funcId);
|
||||
if (!!a.osm !== !!b.osm) return a.osm ? -1 : 1;
|
||||
return b.oppervlakte - a.oppervlakte;
|
||||
});
|
||||
}, [queryResult]);
|
||||
|
||||
if (!queryResult || rows.length === 0) return null;
|
||||
|
||||
const matched = rows.filter((r) => !!r.osm).length;
|
||||
const total = rows.length;
|
||||
const matchPct = Math.round((matched / total) * 100);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
backgroundColor: DMI.white,
|
||||
borderRadius: 12,
|
||||
padding: 20,
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'baseline',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: 6,
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<h3 style={{ ...heading, fontSize: 16, margin: 0 }}>
|
||||
OSM-verrijking — winkel & horeca detail
|
||||
</h3>
|
||||
<span style={{ ...labelMono, fontSize: 11, color: DMI.darkGray }}>
|
||||
{matched}/{total} VBO's ({matchPct}%) gematcht met OpenStreetMap binnen 25 m
|
||||
</span>
|
||||
</div>
|
||||
<p style={{ ...bodyText, fontSize: 12, color: DMI.darkGray, margin: '0 0 14px' }}>
|
||||
BAG geeft alleen <code>winkelfunctie</code> en <code>bijeenkomstfunctie</code> als ruwe
|
||||
categorie. De OSM-tags hieronder bepalen of het naar F2 (Supermarkt), F3 (Retail Food),
|
||||
F4 (Retail Keten), F5 (Retail Onafh.), F6/F7 (Restaurant) of F8 (Café) gaat.
|
||||
VBO's zonder OSM-match krijgen de standaard F5 (winkel) of F7 (horeca).
|
||||
</p>
|
||||
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, minWidth: 720 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: `1px solid ${DMI.blueTint2}` }}>
|
||||
<Th>Functie</Th>
|
||||
<Th>BAG</Th>
|
||||
<Th align="right">m²</Th>
|
||||
<Th>OSM naam</Th>
|
||||
<Th>OSM tags</Th>
|
||||
<Th>VBO id</Th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => {
|
||||
const cfg = BAG_ICONS[r.gebruiksdoel];
|
||||
const Icon = cfg.icon;
|
||||
return (
|
||||
<tr key={r.vboId} style={{ borderBottom: `1px solid ${DMI.blueTint2}` }}>
|
||||
<Td>
|
||||
<strong>{r.funcId}</strong>{' '}
|
||||
<span style={{ color: DMI.darkGray }}>
|
||||
{FUNC_NAME[r.funcId] ?? r.funcId}
|
||||
</span>
|
||||
</Td>
|
||||
<Td>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
<Icon size={12} color={cfg.color} />
|
||||
<span style={{ fontSize: 11, color: DMI.darkGray }}>
|
||||
{r.gebruiksdoel}
|
||||
</span>
|
||||
</span>
|
||||
</Td>
|
||||
<Td align="right">{r.oppervlakte.toLocaleString('nl-NL')}</Td>
|
||||
<Td>
|
||||
{r.osm?.name ? (
|
||||
r.osm.name
|
||||
) : (
|
||||
<em style={{ color: DMI.darkGray }}>—</em>
|
||||
)}
|
||||
</Td>
|
||||
<Td>
|
||||
{r.osm ? (
|
||||
<span style={{ ...labelMono, fontSize: 10 }}>
|
||||
{[
|
||||
r.osm.shop && `shop=${r.osm.shop}`,
|
||||
r.osm.amenity && `amenity=${r.osm.amenity}`,
|
||||
r.osm.brand && `brand=${r.osm.brand}`,
|
||||
r.osm.cuisine && `cuisine=${r.osm.cuisine}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</span>
|
||||
) : (
|
||||
<em style={{ color: DMI.darkGray, fontSize: 11 }}>geen OSM-match</em>
|
||||
)}
|
||||
</Td>
|
||||
<Td>
|
||||
<span style={{ ...labelMono, fontSize: 9, color: DMI.darkGray }}>
|
||||
…{r.vboId.slice(-8)}
|
||||
</span>
|
||||
</Td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Th({ children, align }: { children: React.ReactNode; align?: 'left' | 'right' }) {
|
||||
return (
|
||||
<th
|
||||
style={{
|
||||
padding: '8px 10px',
|
||||
textAlign: align ?? 'left',
|
||||
...labelMono,
|
||||
fontSize: 10,
|
||||
color: DMI.darkBlue,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
function Td({ children, align }: { children: React.ReactNode; align?: 'left' | 'right' }) {
|
||||
return (
|
||||
<td style={{ padding: '8px 10px', textAlign: align ?? 'left', verticalAlign: 'top' }}>
|
||||
{children}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,942 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import maplibregl, { Map as MaplibreMap } from 'maplibre-gl';
|
||||
import 'maplibre-gl/dist/maplibre-gl.css';
|
||||
import {
|
||||
TerraDraw,
|
||||
TerraDrawPolygonMode,
|
||||
TerraDrawFreehandMode,
|
||||
} from 'terra-draw';
|
||||
import { TerraDrawMapLibreGLAdapter } from 'terra-draw-maplibre-gl-adapter';
|
||||
import type {
|
||||
Feature,
|
||||
FeatureCollection,
|
||||
LineString,
|
||||
MultiLineString,
|
||||
MultiPolygon,
|
||||
Polygon,
|
||||
Position,
|
||||
} from 'geojson';
|
||||
import {
|
||||
bbox as turfBbox,
|
||||
buffer as turfBuffer,
|
||||
lineString,
|
||||
nearestPointOnLine,
|
||||
} from '@turf/turf';
|
||||
import {
|
||||
Eraser,
|
||||
Highlighter,
|
||||
Loader2,
|
||||
Magnet,
|
||||
MousePointerClick,
|
||||
PenLine,
|
||||
} from 'lucide-react';
|
||||
import { useApp } from '@/lib/app-context';
|
||||
import { useBag, type BagPolygonFeature } from '@/lib/bag-context';
|
||||
import { BAG_ICONS } from '@/lib/bag-icons';
|
||||
import { mapBagToApplyPlan } from '@/lib/bag-mapping';
|
||||
import { DMI, labelMono, bodyText } from '@/lib/dmi-theme';
|
||||
import type { BagGebruiksdoel, BagQueryResult } from '@/lib/bag-types';
|
||||
import type { LocatieserverLookupResult } from '@/app/api/pdok/lookup/route';
|
||||
import type { PdokReverseResult } from '@/app/api/pdok/reverse/route';
|
||||
import BagAddressSearch from './BagAddressSearch';
|
||||
import BagResultPanel from './BagResultPanel';
|
||||
|
||||
type DrawMode = 'polygon' | 'freehand' | 'idle';
|
||||
|
||||
const BRT_GRIJS_TILE =
|
||||
'https://service.pdok.nl/brt/achtergrondkaart/wmts/v2_0/grijs/EPSG:3857/{z}/{x}/{y}.png';
|
||||
|
||||
const MAP_STYLE = {
|
||||
version: 8 as const,
|
||||
sources: {
|
||||
'pdok-brt': {
|
||||
type: 'raster' as const,
|
||||
tiles: [BRT_GRIJS_TILE],
|
||||
tileSize: 256,
|
||||
attribution: '© <a href="https://www.kadaster.nl/" target="_blank" rel="noopener">Kadaster</a> — BRT',
|
||||
maxzoom: 19,
|
||||
},
|
||||
},
|
||||
layers: [{ id: 'pdok-brt', type: 'raster' as const, source: 'pdok-brt' }],
|
||||
};
|
||||
|
||||
const INITIAL_CENTER: [number, number] = [4.8952, 52.3571];
|
||||
const INITIAL_ZOOM = 15;
|
||||
const SNAP_RADIUS_METERS = 40;
|
||||
const DEFAULT_STREET_BUFFER_METERS = 10;
|
||||
const MIN_BUFFER_METERS = 5;
|
||||
const MAX_BUFFER_METERS = 100;
|
||||
|
||||
const ICON_SIZE = 32;
|
||||
|
||||
type SourceGeometry = LineString | MultiLineString | Polygon | MultiPolygon;
|
||||
|
||||
interface SourceInfo {
|
||||
geometry: SourceGeometry;
|
||||
label: string;
|
||||
isBufferable: boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onApplied?: () => void;
|
||||
panelHeight?: string;
|
||||
}
|
||||
|
||||
export default function BagPanel({ onApplied, panelHeight = 'calc(100vh - 180px)' }: Props) {
|
||||
const { simulation } = useApp();
|
||||
const bag = useBag();
|
||||
|
||||
useEffect(() => {
|
||||
if (!bag.hasVisitedBagTab) {
|
||||
simulation.resetToBlank();
|
||||
bag.markBagTabVisited();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const mapRef = useRef<MaplibreMap | null>(null);
|
||||
const drawRef = useRef<TerraDraw | null>(null);
|
||||
const iconsReadyRef = useRef(false);
|
||||
const [mapReady, setMapReady] = useState(false);
|
||||
const [mode, setMode] = useState<DrawMode>('idle');
|
||||
const [hasPolygon, setHasPolygon] = useState(!!bag.polygon);
|
||||
const [snapping, setSnapping] = useState(false);
|
||||
const [info, setInfo] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [source, setSource] = useState<SourceInfo | null>(null);
|
||||
const [bufferMeters, setBufferMeters] = useState(DEFAULT_STREET_BUFFER_METERS);
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerRef.current || mapRef.current) return;
|
||||
|
||||
const map = new maplibregl.Map({
|
||||
container: containerRef.current,
|
||||
style: MAP_STYLE,
|
||||
center: INITIAL_CENTER,
|
||||
zoom: INITIAL_ZOOM,
|
||||
maxZoom: 19,
|
||||
attributionControl: { compact: true },
|
||||
});
|
||||
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), 'top-right');
|
||||
map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'bottom-left');
|
||||
mapRef.current = map;
|
||||
|
||||
let draw: TerraDraw | null = null;
|
||||
let disposed = false;
|
||||
|
||||
const initDraw = async () => {
|
||||
if (disposed || drawRef.current) return;
|
||||
|
||||
await registerBagIcons(map);
|
||||
iconsReadyRef.current = true;
|
||||
ensurePolygonLayer(map);
|
||||
ensureMarkerLayer(map);
|
||||
wireIconClickHandlers(map);
|
||||
|
||||
draw = new TerraDraw({
|
||||
adapter: new TerraDrawMapLibreGLAdapter({ map }),
|
||||
modes: [
|
||||
new TerraDrawPolygonMode({
|
||||
styles: {
|
||||
fillColor: DMI.mediumBlue,
|
||||
fillOpacity: 0.2,
|
||||
outlineColor: DMI.darkBlue,
|
||||
outlineWidth: 2,
|
||||
closingPointColor: DMI.yellow,
|
||||
closingPointOutlineColor: DMI.darkBlue,
|
||||
closingPointWidth: 2,
|
||||
},
|
||||
}),
|
||||
new TerraDrawFreehandMode({
|
||||
styles: {
|
||||
fillColor: DMI.mediumBlue,
|
||||
fillOpacity: 0.2,
|
||||
outlineColor: DMI.darkBlue,
|
||||
outlineWidth: 2,
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
draw.start();
|
||||
draw.setMode('static');
|
||||
drawRef.current = draw;
|
||||
|
||||
if (bag.polygon) {
|
||||
if (bag.polygon.geometry.type === 'Polygon') {
|
||||
draw.addFeatures([
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
type: 'Feature',
|
||||
geometry: bag.polygon.geometry,
|
||||
properties: { mode: 'polygon' },
|
||||
},
|
||||
]);
|
||||
}
|
||||
setHasPolygon(true);
|
||||
fitToBagPolygon(map, bag.polygon);
|
||||
}
|
||||
|
||||
draw.on('finish', () => {
|
||||
if (!draw) return;
|
||||
const snap = draw.getSnapshot();
|
||||
const poly = snap.find((f) => f.geometry?.type === 'Polygon');
|
||||
if (poly) {
|
||||
const feat: Feature<Polygon> = {
|
||||
type: 'Feature',
|
||||
geometry: poly.geometry as Polygon,
|
||||
properties: {},
|
||||
};
|
||||
setSource(null);
|
||||
bag.setPolygon(feat);
|
||||
setHasPolygon(true);
|
||||
setMode('idle');
|
||||
draw.setMode('static');
|
||||
map.dragPan.enable();
|
||||
map.doubleClickZoom.enable();
|
||||
}
|
||||
});
|
||||
|
||||
setMapReady(true);
|
||||
};
|
||||
|
||||
if (map.isStyleLoaded()) initDraw();
|
||||
else map.once('load', initDraw);
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (draw) draw.stop();
|
||||
map.remove();
|
||||
drawRef.current = null;
|
||||
mapRef.current = null;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!map || !mapReady) return;
|
||||
if (bag.queryResult) {
|
||||
updateMarkers(map, bag.queryResult.features);
|
||||
} else {
|
||||
clearMarkers(map);
|
||||
}
|
||||
}, [bag.queryResult, mapReady]);
|
||||
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!map || !mapReady) return;
|
||||
updatePolygonHighlight(map, bag.polygon);
|
||||
}, [bag.polygon, mapReady]);
|
||||
|
||||
const activate = useCallback(
|
||||
(next: DrawMode) => {
|
||||
const draw = drawRef.current;
|
||||
const map = mapRef.current;
|
||||
if (!draw || !map) return;
|
||||
if (next === 'idle') {
|
||||
draw.setMode('static');
|
||||
map.dragPan.enable();
|
||||
map.doubleClickZoom.enable();
|
||||
setMode('idle');
|
||||
return;
|
||||
}
|
||||
draw.clear();
|
||||
bag.setPolygon(null);
|
||||
bag.setQueryResult(null);
|
||||
setSource(null);
|
||||
setHasPolygon(false);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
map.dragPan.disable();
|
||||
map.doubleClickZoom.disable();
|
||||
draw.setMode(next);
|
||||
setMode(next);
|
||||
},
|
||||
[bag]
|
||||
);
|
||||
|
||||
const handleClear = useCallback(() => {
|
||||
const draw = drawRef.current;
|
||||
const map = mapRef.current;
|
||||
if (!draw || !map) return;
|
||||
draw.clear();
|
||||
bag.reset();
|
||||
setSource(null);
|
||||
setHasPolygon(false);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
draw.setMode('static');
|
||||
map.dragPan.enable();
|
||||
map.doubleClickZoom.enable();
|
||||
setMode('idle');
|
||||
}, [bag]);
|
||||
|
||||
const handleSnap = useCallback(async () => {
|
||||
const draw = drawRef.current;
|
||||
if (!draw || !bag.polygon) return;
|
||||
if (bag.polygon.geometry.type !== 'Polygon') {
|
||||
setError('Snappen werkt alleen op zelf getekende polygonen.');
|
||||
return;
|
||||
}
|
||||
const currentPolygon = bag.polygon as Feature<Polygon>;
|
||||
setSnapping(true);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
try {
|
||||
const [minX, minY, maxX, maxY] = turfBbox(currentPolygon);
|
||||
const pad = 0.002;
|
||||
const params = new URLSearchParams({
|
||||
minX: (minX - pad).toString(),
|
||||
minY: (minY - pad).toString(),
|
||||
maxX: (maxX + pad).toString(),
|
||||
maxY: (maxY + pad).toString(),
|
||||
});
|
||||
const resp = await fetch(`/api/nwb/streets?${params.toString()}`);
|
||||
if (!resp.ok) {
|
||||
const { error: msg } = await resp.json().catch(() => ({ error: `NWB ${resp.status}` }));
|
||||
setError(msg ?? 'Straten konden niet worden geladen.');
|
||||
return;
|
||||
}
|
||||
const fc = (await resp.json()) as FeatureCollection;
|
||||
const segments = fc.features
|
||||
.filter((f): f is Feature<LineString> => f.geometry?.type === 'LineString')
|
||||
.map((f) => lineString(f.geometry.coordinates));
|
||||
if (segments.length === 0) {
|
||||
setInfo('Geen straatgeometrie gevonden — polygon ongewijzigd.');
|
||||
return;
|
||||
}
|
||||
const ring = currentPolygon.geometry.coordinates[0];
|
||||
let snapped = 0;
|
||||
const snappedRing: Position[] = ring.map((pt) => {
|
||||
let bestCoord: Position | null = null;
|
||||
let bestDist = Infinity;
|
||||
for (const seg of segments) {
|
||||
const npo = nearestPointOnLine(seg, pt as Position, { units: 'meters' });
|
||||
const d = (npo.properties as { dist?: number }).dist ?? Infinity;
|
||||
if (d < bestDist) {
|
||||
bestDist = d;
|
||||
bestCoord = npo.geometry.coordinates;
|
||||
}
|
||||
}
|
||||
if (bestCoord && bestDist < SNAP_RADIUS_METERS) {
|
||||
snapped += 1;
|
||||
return bestCoord;
|
||||
}
|
||||
return pt;
|
||||
});
|
||||
const first = snappedRing[0];
|
||||
const last = snappedRing[snappedRing.length - 1];
|
||||
if (first[0] !== last[0] || first[1] !== last[1]) snappedRing.push(first);
|
||||
const snappedPoly: Feature<Polygon> = {
|
||||
type: 'Feature',
|
||||
geometry: { type: 'Polygon', coordinates: [snappedRing] },
|
||||
properties: {},
|
||||
};
|
||||
draw.clear();
|
||||
draw.addFeatures([
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
type: 'Feature',
|
||||
geometry: snappedPoly.geometry,
|
||||
properties: { mode: 'polygon' },
|
||||
},
|
||||
]);
|
||||
bag.setPolygon(snappedPoly);
|
||||
setInfo(`${snapped}/${ring.length} punten gehecht aan straten.`);
|
||||
} catch (err) {
|
||||
setError(`Snap mislukt: ${(err as Error).message}`);
|
||||
} finally {
|
||||
setSnapping(false);
|
||||
}
|
||||
}, [bag]);
|
||||
|
||||
const handleQuery = useCallback(async () => {
|
||||
if (!bag.polygon) return;
|
||||
bag.setQuerying(true);
|
||||
setError(null);
|
||||
bag.setQueryError(null);
|
||||
try {
|
||||
const resp = await fetch('/api/bag/query', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ polygon: bag.polygon }),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const { error: msg } = await resp.json().catch(() => ({ error: `BAG ${resp.status}` }));
|
||||
setError(msg ?? 'BAG-query mislukt.');
|
||||
bag.setQueryError(msg ?? null);
|
||||
return;
|
||||
}
|
||||
const result = (await resp.json()) as BagQueryResult;
|
||||
bag.setQueryResult(result);
|
||||
} catch (err) {
|
||||
setError(`BAG-query mislukt: ${(err as Error).message}`);
|
||||
} finally {
|
||||
bag.setQuerying(false);
|
||||
}
|
||||
}, [bag]);
|
||||
|
||||
const handleAddressSelect = useCallback(
|
||||
(lookup: LocatieserverLookupResult) => {
|
||||
const map = mapRef.current;
|
||||
const draw = drawRef.current;
|
||||
if (!map || !draw) return;
|
||||
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
draw.clear();
|
||||
|
||||
if (lookup.geometry) {
|
||||
const g = lookup.geometry;
|
||||
const isLine = g.type === 'LineString' || g.type === 'MultiLineString';
|
||||
setSource({
|
||||
geometry: g,
|
||||
label: lookup.weergavenaam,
|
||||
isBufferable: isLine || lookup.type === 'weg',
|
||||
});
|
||||
setInfo(
|
||||
isLine
|
||||
? `${lookup.weergavenaam} — stel de buffer in en klik BAG ophalen.`
|
||||
: `${lookup.weergavenaam} geselecteerd. Klik BAG ophalen.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (lookup.centroid) {
|
||||
setSource(null);
|
||||
bag.setPolygon(null);
|
||||
setHasPolygon(false);
|
||||
map.flyTo({ center: lookup.centroid.coordinates as [number, number], zoom: 17 });
|
||||
setInfo('Ingezoomd. Teken zelf een polygon om dit adres.');
|
||||
}
|
||||
},
|
||||
[bag]
|
||||
);
|
||||
|
||||
// Recompute buffered polygon whenever source or bufferMeters change.
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!map || !source) return;
|
||||
let poly: BagPolygonFeature | null = null;
|
||||
if (source.isBufferable) {
|
||||
try {
|
||||
const buffered = turfBuffer(
|
||||
{ type: 'Feature', geometry: source.geometry, properties: {} },
|
||||
bufferMeters,
|
||||
{ units: 'meters' }
|
||||
);
|
||||
if (buffered?.geometry) {
|
||||
poly = {
|
||||
type: 'Feature',
|
||||
geometry: buffered.geometry as Polygon | MultiPolygon,
|
||||
properties: {},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
} else if (source.geometry.type === 'Polygon' || source.geometry.type === 'MultiPolygon') {
|
||||
poly = { type: 'Feature', geometry: source.geometry, properties: {} };
|
||||
}
|
||||
if (poly) {
|
||||
bag.setPolygon(poly);
|
||||
bag.setQueryResult(null);
|
||||
setHasPolygon(true);
|
||||
fitToBagPolygon(map, poly);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [source, bufferMeters]);
|
||||
|
||||
const handleApply = useCallback(
|
||||
(plan: ReturnType<typeof mapBagToApplyPlan>) => {
|
||||
simulation.handleApplyBagPlan(plan);
|
||||
onApplied?.();
|
||||
},
|
||||
[simulation, onApplied]
|
||||
);
|
||||
|
||||
const modeLabel =
|
||||
mode === 'polygon'
|
||||
? 'Klik punten, dubbelklik om te sluiten'
|
||||
: mode === 'freehand'
|
||||
? 'Sleep om vrije hand te tekenen'
|
||||
: hasPolygon
|
||||
? 'Polygon getekend'
|
||||
: 'Zoek een straat of kies een tekentool';
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
height: panelHeight,
|
||||
minHeight: 500,
|
||||
gap: 12,
|
||||
backgroundColor: DMI.blueTint2,
|
||||
padding: 12,
|
||||
borderRadius: 10,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
flex: 1,
|
||||
minWidth: 320,
|
||||
borderRadius: 8,
|
||||
overflow: 'hidden',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
|
||||
}}
|
||||
>
|
||||
<div ref={containerRef} style={{ position: 'absolute', inset: 0 }} />
|
||||
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 10,
|
||||
left: 10,
|
||||
right: 10,
|
||||
display: 'flex',
|
||||
gap: 8,
|
||||
alignItems: 'flex-start',
|
||||
zIndex: 20,
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: 1, minWidth: 220, maxWidth: 460 }}>
|
||||
<BagAddressSearch onSelect={handleAddressSelect} />
|
||||
</div>
|
||||
<button
|
||||
onClick={handleQuery}
|
||||
disabled={!hasPolygon || bag.isQuerying}
|
||||
style={{
|
||||
backgroundColor: hasPolygon && !bag.isQuerying ? DMI.yellow : DMI.darkGray,
|
||||
color: DMI.darkBlue,
|
||||
border: 'none',
|
||||
padding: '8px 14px',
|
||||
borderRadius: 6,
|
||||
cursor: hasPolygon && !bag.isQuerying ? 'pointer' : 'not-allowed',
|
||||
fontWeight: 600,
|
||||
fontSize: 12,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
opacity: hasPolygon && !bag.isQuerying ? 1 : 0.5,
|
||||
whiteSpace: 'nowrap',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
{bag.isQuerying ? (
|
||||
<Loader2 size={12} className="animate-spin" />
|
||||
) : (
|
||||
<MousePointerClick size={12} />
|
||||
)}
|
||||
BAG ophalen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{source?.isBufferable && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 56,
|
||||
right: 48,
|
||||
backgroundColor: DMI.white,
|
||||
padding: '8px 14px',
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 2px 6px rgba(0,0,0,0.12)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
zIndex: 15,
|
||||
minWidth: 260,
|
||||
}}
|
||||
>
|
||||
<span style={{ ...labelMono, fontSize: 10, color: DMI.darkBlue }}>BUFFER</span>
|
||||
<input
|
||||
type="range"
|
||||
min={MIN_BUFFER_METERS}
|
||||
max={MAX_BUFFER_METERS}
|
||||
step={5}
|
||||
value={bufferMeters}
|
||||
onChange={(e) => setBufferMeters(Number(e.target.value))}
|
||||
style={{ flex: 1, accentColor: DMI.darkBlue }}
|
||||
/>
|
||||
<span
|
||||
style={{
|
||||
...labelMono,
|
||||
fontSize: 11,
|
||||
color: DMI.darkBlue,
|
||||
fontWeight: 600,
|
||||
minWidth: 36,
|
||||
textAlign: 'right',
|
||||
}}
|
||||
>
|
||||
{bufferMeters} m
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 60,
|
||||
left: 10,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 6,
|
||||
backgroundColor: DMI.white,
|
||||
padding: 6,
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 2px 6px rgba(0,0,0,0.12)',
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
<ToolButton
|
||||
active={mode === 'polygon'}
|
||||
onClick={() => activate(mode === 'polygon' ? 'idle' : 'polygon')}
|
||||
icon={<PenLine size={14} />}
|
||||
label="Polygon"
|
||||
/>
|
||||
<ToolButton
|
||||
active={mode === 'freehand'}
|
||||
onClick={() => activate(mode === 'freehand' ? 'idle' : 'freehand')}
|
||||
icon={<Highlighter size={14} />}
|
||||
label="Vrije hand"
|
||||
/>
|
||||
<div style={{ height: 1, backgroundColor: DMI.blueTint2, margin: '2px 0' }} />
|
||||
<ToolButton
|
||||
active={false}
|
||||
disabled={!hasPolygon || snapping}
|
||||
onClick={handleSnap}
|
||||
icon={snapping ? <Loader2 size={14} className="animate-spin" /> : <Magnet size={14} />}
|
||||
label={snapping ? 'Hechten…' : 'Straat-snap'}
|
||||
/>
|
||||
<ToolButton
|
||||
active={false}
|
||||
disabled={!hasPolygon}
|
||||
onClick={handleClear}
|
||||
icon={<Eraser size={14} />}
|
||||
label="Wissen"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 10,
|
||||
left: 10,
|
||||
backgroundColor: 'rgba(255,255,255,0.92)',
|
||||
padding: '4px 10px',
|
||||
borderRadius: 4,
|
||||
fontSize: 10,
|
||||
...labelMono,
|
||||
color: DMI.darkBlue,
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
{modeLabel}
|
||||
</div>
|
||||
|
||||
{info && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 38,
|
||||
left: 10,
|
||||
right: 10,
|
||||
backgroundColor: DMI.white,
|
||||
color: DMI.darkBlue,
|
||||
padding: '6px 10px',
|
||||
borderRadius: 4,
|
||||
fontSize: 12,
|
||||
...bodyText,
|
||||
boxShadow: '0 2px 6px rgba(0,0,0,0.12)',
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
{info}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
width: 360,
|
||||
flexShrink: 0,
|
||||
backgroundColor: DMI.white,
|
||||
borderRadius: 8,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
|
||||
}}
|
||||
>
|
||||
<BagResultPanel
|
||||
result={bag.queryResult}
|
||||
isQuerying={bag.isQuerying}
|
||||
error={error ?? bag.queryError}
|
||||
onApply={handleApply}
|
||||
onReset={handleClear}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolButton({
|
||||
active,
|
||||
disabled,
|
||||
onClick,
|
||||
icon,
|
||||
label,
|
||||
}: {
|
||||
active: boolean;
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
padding: '6px 10px',
|
||||
borderRadius: 4,
|
||||
border: `1px solid ${active ? DMI.darkBlue : DMI.blueTint2}`,
|
||||
backgroundColor: active ? DMI.darkBlue : DMI.white,
|
||||
color: active ? DMI.white : DMI.darkBlue,
|
||||
cursor: disabled ? 'not-allowed' : 'pointer',
|
||||
opacity: disabled ? 0.5 : 1,
|
||||
fontSize: 11,
|
||||
fontFamily: 'inherit',
|
||||
minWidth: 120,
|
||||
textAlign: 'left',
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function fitToBagPolygon(map: MaplibreMap, polygon: BagPolygonFeature) {
|
||||
const [minX, minY, maxX, maxY] = turfBbox(polygon);
|
||||
map.fitBounds(
|
||||
[
|
||||
[minX, minY],
|
||||
[maxX, maxY],
|
||||
],
|
||||
{ padding: 60, duration: 600 }
|
||||
);
|
||||
}
|
||||
|
||||
async function registerBagIcons(map: MaplibreMap) {
|
||||
for (const [key, cfg] of Object.entries(BAG_ICONS)) {
|
||||
const imageName = `bag-${key}`;
|
||||
if (map.hasImage(imageName)) continue;
|
||||
const svgMarkup = renderToStaticMarkup(
|
||||
<cfg.icon size={ICON_SIZE - 10} color={cfg.color} strokeWidth={2.5} />
|
||||
);
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${ICON_SIZE}" height="${ICON_SIZE}" viewBox="0 0 ${ICON_SIZE} ${ICON_SIZE}">
|
||||
<circle cx="${ICON_SIZE / 2}" cy="${ICON_SIZE / 2}" r="${ICON_SIZE / 2 - 1}" fill="white" stroke="${cfg.color}" stroke-width="1.5" />
|
||||
<g transform="translate(5,5)">${svgMarkup}</g>
|
||||
</svg>`;
|
||||
const blob = new Blob([svg], { type: 'image/svg+xml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const img = await loadImage(url);
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = ICON_SIZE;
|
||||
canvas.height = ICON_SIZE;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) continue;
|
||||
ctx.drawImage(img, 0, 0, ICON_SIZE, ICON_SIZE);
|
||||
const imageData = ctx.getImageData(0, 0, ICON_SIZE, ICON_SIZE);
|
||||
map.addImage(imageName, imageData);
|
||||
} finally {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function loadImage(src: string): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve(img);
|
||||
img.onerror = reject;
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
|
||||
function ensureMarkerLayer(map: MaplibreMap) {
|
||||
if (!map.getSource('bag-vbo')) {
|
||||
map.addSource('bag-vbo', {
|
||||
type: 'geojson',
|
||||
data: { type: 'FeatureCollection', features: [] },
|
||||
});
|
||||
}
|
||||
if (!map.getLayer('bag-vbo-icons')) {
|
||||
map.addLayer({
|
||||
id: 'bag-vbo-icons',
|
||||
source: 'bag-vbo',
|
||||
type: 'symbol',
|
||||
layout: {
|
||||
'icon-image': ['concat', 'bag-', ['get', 'gebruiksdoel']],
|
||||
'icon-size': 0.6,
|
||||
'icon-allow-overlap': true,
|
||||
'icon-ignore-placement': true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function wireIconClickHandlers(map: MaplibreMap) {
|
||||
let activePopup: maplibregl.Popup | null = null;
|
||||
|
||||
map.on('click', 'bag-vbo-icons', async (e) => {
|
||||
const feat = e.features?.[0];
|
||||
if (!feat || feat.geometry.type !== 'Point') return;
|
||||
const coords = feat.geometry.coordinates as [number, number];
|
||||
const rawProps = feat.properties as { gebruiksdoel: BagGebruiksdoel; oppervlakte: number; osm?: string };
|
||||
// MapLibre flattens object props to JSON strings
|
||||
const osmTags = typeof rawProps.osm === 'string' ? JSON.parse(rawProps.osm) : (rawProps.osm as object | undefined);
|
||||
const cfg = BAG_ICONS[rawProps.gebruiksdoel];
|
||||
if (!cfg) return;
|
||||
|
||||
if (activePopup) activePopup.remove();
|
||||
activePopup = new maplibregl.Popup({ closeButton: true, maxWidth: '300px', offset: 12 })
|
||||
.setLngLat(coords)
|
||||
.setHTML(buildPopupHtml(cfg, rawProps.oppervlakte, null, true, osmTags))
|
||||
.addTo(map);
|
||||
|
||||
try {
|
||||
const resp = await fetch(`/api/pdok/reverse?lat=${coords[1]}&lon=${coords[0]}`);
|
||||
if (!resp.ok) {
|
||||
activePopup.setHTML(buildPopupHtml(cfg, rawProps.oppervlakte, null, false, osmTags));
|
||||
return;
|
||||
}
|
||||
const data = (await resp.json()) as PdokReverseResult;
|
||||
activePopup.setHTML(buildPopupHtml(cfg, rawProps.oppervlakte, data.weergavenaam, false, osmTags));
|
||||
} catch {
|
||||
activePopup.setHTML(buildPopupHtml(cfg, rawProps.oppervlakte, null, false, osmTags));
|
||||
}
|
||||
});
|
||||
|
||||
map.on('mouseenter', 'bag-vbo-icons', () => {
|
||||
map.getCanvas().style.cursor = 'pointer';
|
||||
});
|
||||
map.on('mouseleave', 'bag-vbo-icons', () => {
|
||||
map.getCanvas().style.cursor = '';
|
||||
});
|
||||
}
|
||||
|
||||
function buildPopupHtml(
|
||||
cfg: { label: string; color: string; icon: React.ComponentType<{ size?: number; color?: string; strokeWidth?: number }> },
|
||||
oppervlakte: number,
|
||||
address: string | null,
|
||||
loading: boolean,
|
||||
osm?: { name?: string; shop?: string; amenity?: string; brand?: string; cuisine?: string }
|
||||
): string {
|
||||
const Icon = cfg.icon;
|
||||
const iconSvg = renderToStaticMarkup(<Icon size={18} color={cfg.color} strokeWidth={2.2} />);
|
||||
const addressLine = loading
|
||||
? `<em style="color:#888;">Adres ophalen…</em>`
|
||||
: address
|
||||
? `<div style="color:#0a3660;">${escapeHtml(address)}</div>`
|
||||
: `<em style="color:#888;">Geen adres gevonden</em>`;
|
||||
|
||||
let osmBlock = '';
|
||||
if (osm && (osm.name || osm.shop || osm.amenity)) {
|
||||
const parts: string[] = [];
|
||||
if (osm.name) parts.push(`<strong>${escapeHtml(osm.name)}</strong>`);
|
||||
const tags: string[] = [];
|
||||
if (osm.shop) tags.push(`shop=${escapeHtml(osm.shop)}`);
|
||||
if (osm.amenity) tags.push(`amenity=${escapeHtml(osm.amenity)}`);
|
||||
if (osm.brand) tags.push(`brand=${escapeHtml(osm.brand)}`);
|
||||
if (osm.cuisine) tags.push(`cuisine=${escapeHtml(osm.cuisine)}`);
|
||||
if (tags.length) parts.push(`<span style="font-family: var(--font-ibm-plex-mono), ui-monospace, monospace; font-size:10px; color:#565656;">${tags.join(' · ')}</span>`);
|
||||
osmBlock = `<div style="margin-top:6px; padding:6px 8px; background:#f4f8fc; border-left:2px solid ${cfg.color}; border-radius:3px; font-size:11px;">${parts.join('<br>')}<div style="font-size:9px; color:#888; margin-top:2px;">via OpenStreetMap</div></div>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div style="font-family: var(--font-ibm-plex-sans), system-ui, sans-serif; padding: 4px 2px;">
|
||||
<div style="display:flex; align-items:center; gap:8px; margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid #daebfb;">
|
||||
${iconSvg}
|
||||
<strong style="font-size:13px; color:${cfg.color};">${escapeHtml(cfg.label)}</strong>
|
||||
</div>
|
||||
<div style="font-size:12px; line-height:1.45;">${addressLine}</div>
|
||||
<div style="font-size:11px; color:#565656; margin-top:4px; font-family: var(--font-ibm-plex-mono), ui-monospace, monospace;">${oppervlakte.toLocaleString('nl-NL')} m²</div>
|
||||
${osmBlock}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
return str.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] ?? c));
|
||||
}
|
||||
|
||||
function updateMarkers(
|
||||
map: MaplibreMap,
|
||||
fc: FeatureCollection<GeoJSON.Point, { gebruiksdoel: BagGebruiksdoel; oppervlakte: number; id?: string }>
|
||||
) {
|
||||
const src = map.getSource('bag-vbo');
|
||||
if (src && 'setData' in src) {
|
||||
(src as maplibregl.GeoJSONSource).setData(fc);
|
||||
}
|
||||
}
|
||||
|
||||
function clearMarkers(map: MaplibreMap) {
|
||||
const src = map.getSource('bag-vbo');
|
||||
if (src && 'setData' in src) {
|
||||
(src as maplibregl.GeoJSONSource).setData({ type: 'FeatureCollection', features: [] });
|
||||
}
|
||||
}
|
||||
|
||||
function ensurePolygonLayer(map: MaplibreMap) {
|
||||
if (!map.getSource('bag-selection')) {
|
||||
map.addSource('bag-selection', {
|
||||
type: 'geojson',
|
||||
data: { type: 'FeatureCollection', features: [] },
|
||||
});
|
||||
}
|
||||
if (!map.getLayer('bag-selection-fill')) {
|
||||
map.addLayer({
|
||||
id: 'bag-selection-fill',
|
||||
source: 'bag-selection',
|
||||
type: 'fill',
|
||||
paint: {
|
||||
'fill-color': DMI.mediumBlue,
|
||||
'fill-opacity': 0.18,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!map.getLayer('bag-selection-outline')) {
|
||||
map.addLayer({
|
||||
id: 'bag-selection-outline',
|
||||
source: 'bag-selection',
|
||||
type: 'line',
|
||||
paint: {
|
||||
'line-color': DMI.darkBlue,
|
||||
'line-width': 2,
|
||||
'line-dasharray': [2, 2],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function updatePolygonHighlight(map: MaplibreMap, polygon: BagPolygonFeature | null) {
|
||||
const src = map.getSource('bag-selection');
|
||||
if (!src || !('setData' in src)) return;
|
||||
const data: FeatureCollection = polygon
|
||||
? { type: 'FeatureCollection', features: [polygon] }
|
||||
: { type: 'FeatureCollection', features: [] };
|
||||
(src as maplibregl.GeoJSONSource).setData(data);
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { AlertTriangle, Check, Info, Loader2, XCircle } from 'lucide-react';
|
||||
import { DMI, heading, bodyText, labelMono } from '@/lib/dmi-theme';
|
||||
import { BAG_ICONS } from '@/lib/bag-icons';
|
||||
import { mapBagToApplyPlan } from '@/lib/bag-mapping';
|
||||
import type { BagQueryResult } from '@/lib/bag-types';
|
||||
|
||||
interface Props {
|
||||
result: BagQueryResult | null;
|
||||
isQuerying: boolean;
|
||||
error: string | null;
|
||||
onApply: (plan: ReturnType<typeof mapBagToApplyPlan>) => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
|
||||
export default function BagResultPanel({ result, isQuerying, error, onApply, onReset }: Props) {
|
||||
const plan = useMemo(() => (result ? mapBagToApplyPlan(result) : null), [result]);
|
||||
|
||||
if (isQuerying) {
|
||||
return (
|
||||
<Empty>
|
||||
<Loader2 size={18} className="animate-spin" />
|
||||
<span>BAG wordt opgehaald…</span>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Empty>
|
||||
<XCircle size={20} color={DMI.yellow} />
|
||||
<span style={{ ...bodyText, fontSize: 13 }}>{error}</span>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
if (!result || !plan) {
|
||||
return (
|
||||
<Empty>
|
||||
<Info size={20} color={DMI.mediumBlue} />
|
||||
<div style={{ ...bodyText, fontSize: 13, maxWidth: 260, textAlign: 'center' }}>
|
||||
Zoek een straat of teken een polygon op de kaart en klik <strong>BAG ophalen</strong>.
|
||||
</div>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
const totalMapped = plan.mapping.reduce((sum, m) => sum + m.count, 0);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14, overflowY: 'auto' }}>
|
||||
<div>
|
||||
<h3 style={{ ...heading, fontSize: 15, margin: 0 }}>BAG-resultaat</h3>
|
||||
<p style={{ ...bodyText, fontSize: 12, color: DMI.darkGray, margin: '2px 0 0' }}>
|
||||
{result.totalVerblijfsobjecten} verblijfsobjecten in geselecteerd gebied
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{result.truncated && (
|
||||
<Banner tone="warn" icon={<AlertTriangle size={14} />}>
|
||||
Gebied te groot — resultaten afgekapt. Maak het gebied kleiner.
|
||||
</Banner>
|
||||
)}
|
||||
{result.multiUseCount > 0 && (
|
||||
<Banner tone="info">
|
||||
{result.multiUseCount} panden met meerdere gebruiksdoelen — eerste geteld.
|
||||
</Banner>
|
||||
)}
|
||||
|
||||
<Section title="Verdeling per gebruiksdoel">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
{Object.values(result.buckets)
|
||||
.filter((b): b is NonNullable<typeof b> => !!b)
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.map((bucket) => {
|
||||
const cfg = BAG_ICONS[bucket.gebruiksdoel];
|
||||
const Icon = cfg.icon;
|
||||
return (
|
||||
<div
|
||||
key={bucket.gebruiksdoel}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
padding: '6px 10px',
|
||||
borderRadius: 4,
|
||||
backgroundColor: DMI.blueTint2,
|
||||
}}
|
||||
>
|
||||
<Icon size={14} color={cfg.color} />
|
||||
<span style={{ fontSize: 12, flex: 1 }}>{cfg.label}</span>
|
||||
<span style={{ ...labelMono, fontSize: 11 }}>
|
||||
{bucket.count} · {Math.round(bucket.totalOppervlakte).toLocaleString('nl-NL')} m²
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Overnemen in model">
|
||||
{plan.mapping.length === 0 ? (
|
||||
<p style={{ ...bodyText, color: DMI.darkGray, margin: 0, fontSize: 12 }}>
|
||||
Geen gebruiksdoelen konden worden gemapt op de 12 functies.
|
||||
</p>
|
||||
) : (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: `1px solid ${DMI.blueTint2}` }}>
|
||||
<Th>Functie</Th>
|
||||
<Th align="right">Aantal</Th>
|
||||
<Th align="right">m²</Th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{plan.mapping.map((m, i) => (
|
||||
<tr key={i} style={{ borderBottom: `1px solid ${DMI.blueTint2}` }}>
|
||||
<Td>
|
||||
<strong>{m.toFuncId}</strong> {m.toFuncName}
|
||||
<div style={{ ...labelMono, fontSize: 9, color: DMI.darkGray, marginTop: 1 }}>
|
||||
← {m.from}
|
||||
</div>
|
||||
</Td>
|
||||
<Td align="right">{m.count}</Td>
|
||||
<Td align="right">{m.totalBvo.toLocaleString('nl-NL')}</Td>
|
||||
</tr>
|
||||
))}
|
||||
<tr style={{ fontWeight: 600 }}>
|
||||
<Td>Totaal</Td>
|
||||
<Td align="right">{totalMapped}</Td>
|
||||
<Td align="right">
|
||||
{plan.mapping.reduce((s, m) => s + m.totalBvo, 0).toLocaleString('nl-NL')}
|
||||
</Td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{plan.unmappedBuckets.length > 0 && (
|
||||
<Section title="Niet gemapt">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
{plan.unmappedBuckets.map((b) => {
|
||||
const cfg = BAG_ICONS[b.gebruiksdoel];
|
||||
const Icon = cfg.icon;
|
||||
return (
|
||||
<div key={b.gebruiksdoel} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
|
||||
<Icon size={12} color={cfg.color} />
|
||||
<span style={{ flex: 1 }}>{cfg.label}</span>
|
||||
<span style={{ ...labelMono, fontSize: 10 }}>
|
||||
{b.count} · {Math.round(b.totalOppervlakte).toLocaleString('nl-NL')} m²
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 4 }}>
|
||||
<button
|
||||
onClick={() => plan && onApply(plan)}
|
||||
disabled={plan.mapping.length === 0}
|
||||
style={{
|
||||
padding: '10px 16px',
|
||||
borderRadius: 6,
|
||||
border: 'none',
|
||||
backgroundColor: plan.mapping.length === 0 ? DMI.darkGray : DMI.yellow,
|
||||
color: DMI.darkBlue,
|
||||
fontWeight: 600,
|
||||
cursor: plan.mapping.length === 0 ? 'not-allowed' : 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 8,
|
||||
fontFamily: 'inherit',
|
||||
opacity: plan.mapping.length === 0 ? 0.5 : 1,
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
<Check size={14} /> Overnemen in Ruimtemodel
|
||||
</button>
|
||||
<button
|
||||
onClick={onReset}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
borderRadius: 6,
|
||||
border: `1px solid ${DMI.blueTint2}`,
|
||||
backgroundColor: DMI.white,
|
||||
color: DMI.darkBlue,
|
||||
cursor: 'pointer',
|
||||
fontFamily: 'inherit',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
Opnieuw
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p style={{ ...labelMono, fontSize: 9, color: DMI.darkGray, textAlign: 'right', marginTop: 4 }}>
|
||||
{new Date(result.queriedAt).toLocaleString('nl-NL')} · PDOK BAG WFS
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Empty({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 10,
|
||||
padding: 20,
|
||||
color: DMI.darkGray,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<h4 style={{ ...labelMono, fontSize: 10, margin: '0 0 6px', color: DMI.darkBlue }}>{title}</h4>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Banner({ tone, icon, children }: { tone: 'info' | 'warn'; icon?: React.ReactNode; children: React.ReactNode }) {
|
||||
const bg = tone === 'warn' ? '#fff7e6' : DMI.blueTint2;
|
||||
const border = tone === 'warn' ? DMI.yellow : DMI.mediumBlue;
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
padding: '8px 10px',
|
||||
backgroundColor: bg,
|
||||
borderLeft: `3px solid ${border}`,
|
||||
borderRadius: 3,
|
||||
fontSize: 11,
|
||||
...bodyText,
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
<span>{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Th({ children, align }: { children: React.ReactNode; align?: 'left' | 'right' }) {
|
||||
return (
|
||||
<th style={{ padding: '6px 8px', textAlign: align ?? 'left', ...labelMono, fontSize: 10 }}>
|
||||
{children}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
function Td({ children, align }: { children: React.ReactNode; align?: 'left' | 'right' }) {
|
||||
return (
|
||||
<td style={{ padding: '6px 8px', textAlign: align ?? 'left', verticalAlign: 'top' }}>
|
||||
{children}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
ChevronUp,
|
||||
Play,
|
||||
Info,
|
||||
Map as MapIcon,
|
||||
} from 'lucide-react';
|
||||
import dynamic from 'next/dynamic';
|
||||
const BagPanel = dynamic(() => import('@/components/bag/BagPanel'), { ssr: false });
|
||||
const BagOsmDetails = dynamic(() => import('@/components/bag/BagOsmDetails'), { ssr: false });
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
@@ -178,7 +182,7 @@ function EmptyState({ message }: { message: string }) {
|
||||
// Main Layout Component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type DmiNavMode = 'cockpit' | 'cover' | 'handleiding' | 'parameters';
|
||||
type DmiNavMode = 'cockpit' | 'cover' | 'handleiding' | 'parameters' | 'bag';
|
||||
type HandleidingSubTab = 'handleiding' | 'casus';
|
||||
|
||||
export default function DmiCockpitLayout({
|
||||
@@ -344,7 +348,7 @@ export default function DmiCockpitLayout({
|
||||
margin: '4px 0 0 0',
|
||||
}}
|
||||
>
|
||||
{navMode === 'cockpit' ? 'Spreadsheet' : navMode === 'cover' ? 'Cover' : navMode === 'parameters' ? 'Parameters' : 'Handleiding'}
|
||||
{navMode === 'cockpit' ? 'Spreadsheet' : navMode === 'cover' ? 'Cover' : navMode === 'parameters' ? 'Parameters' : navMode === 'bag' ? 'BAG-gebied' : 'Handleiding'}
|
||||
</p>
|
||||
</div>
|
||||
{isMobile && (
|
||||
@@ -360,7 +364,7 @@ export default function DmiCockpitLayout({
|
||||
</div>
|
||||
{/* Nav buttons */}
|
||||
<div data-tutorial="nav-tabs" style={{ display: 'flex', gap: '4px', overflowX: 'auto', WebkitOverflowScrolling: 'touch', width: isMobile ? '100%' : 'auto' }}>
|
||||
{(['cover', 'handleiding', 'cockpit', 'parameters'] as DmiNavMode[]).map((mode) => (
|
||||
{(['cover', 'handleiding', 'cockpit', 'bag', 'parameters'] as DmiNavMode[]).map((mode) => (
|
||||
<button
|
||||
key={mode}
|
||||
onClick={() => setNavMode(mode)}
|
||||
@@ -380,7 +384,7 @@ export default function DmiCockpitLayout({
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
{mode === 'cockpit' ? 'Spreadsheet' : mode}
|
||||
{mode === 'cockpit' ? 'Spreadsheet' : mode === 'bag' ? 'BAG-gebied' : mode}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -853,6 +857,28 @@ export default function DmiCockpitLayout({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ================================================================
|
||||
BAG-GEBIED VIEW
|
||||
================================================================ */}
|
||||
{navMode === 'bag' && (
|
||||
<div style={{ padding: isMobile ? '16px' : '24px', maxWidth: '1400px', margin: '0 auto' }}>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<h2 style={{ ...heading, fontSize: isMobile ? '1.1rem' : '1.3rem', margin: 0 }}>
|
||||
BAG-gebied inladen
|
||||
</h2>
|
||||
<p style={{ ...bodyText, fontSize: 12, color: DMI.darkGray, margin: '4px 0 0', maxWidth: 760 }}>
|
||||
Zoek een straat of teken een gebied. Klik BAG ophalen om de verblijfsobjecten uit PDOK BAG te tellen
|
||||
en over te nemen in de spreadsheet.
|
||||
</p>
|
||||
</div>
|
||||
<BagPanel
|
||||
panelHeight="calc(100vh - 220px)"
|
||||
onApplied={() => setNavMode('cockpit')}
|
||||
/>
|
||||
<BagOsmDetails />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ================================================================
|
||||
PARAMETERS VIEW
|
||||
================================================================ */}
|
||||
@@ -975,6 +1001,18 @@ export default function DmiCockpitLayout({
|
||||
<div data-tutorial="function-inputs">
|
||||
<Panel title="Inventarisatie Functies">
|
||||
<div style={{ display: 'flex', gap: '6px', marginBottom: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<button
|
||||
onClick={() => setNavMode('bag')}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: '4px',
|
||||
padding: '4px 10px', borderRadius: '4px', border: `1px solid ${DMI.darkBlue}`,
|
||||
backgroundColor: DMI.darkBlue, color: DMI.white,
|
||||
fontFamily: 'var(--font-ibm-plex-sans), sans-serif',
|
||||
fontWeight: 500, fontSize: '0.65rem', cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
<MapIcon size={11} /> BAG-gebied
|
||||
</button>
|
||||
<button
|
||||
data-tutorial="preset-gerard"
|
||||
onClick={state.resetToGerardDoustraat}
|
||||
|
||||
@@ -5,7 +5,10 @@ import type { SimulationState, LayoutType } from '@/lib/use-simulation-state';
|
||||
import { VEHICLES, FUNCTIONS, LOADING_BAY_WIDTH_M } from '@/lib/model-data';
|
||||
import { DMI, PERIOD_COLORS, FUNCTION_COLORS, CLUSTER_COLORS, SERVICE_LEVEL_OPTIONS, MAX_CLUSTERS, heading, bodyText, labelMono } from '@/lib/dmi-theme';
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer, Cell, PieChart, Pie, LineChart, Line } from 'recharts';
|
||||
import { Loader2, Play, LayoutDashboard, ClipboardList, Network, BarChart3, ChevronDown, ChevronUp, Info, BookOpen, MapPin, RotateCcw, Settings, FileDown, FileText, Printer } from 'lucide-react';
|
||||
import { Loader2, Play, LayoutDashboard, ClipboardList, Network, BarChart3, ChevronDown, ChevronUp, Info, BookOpen, MapPin, RotateCcw, Settings, FileDown, FileText, Printer, Map } from 'lucide-react';
|
||||
import dynamic from 'next/dynamic';
|
||||
const BagPanel = dynamic(() => import('@/components/bag/BagPanel'), { ssr: false });
|
||||
const BagOsmDetails = dynamic(() => import('@/components/bag/BagOsmDetails'), { ssr: false });
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import FeedbackButton from '@/components/FeedbackButton';
|
||||
@@ -19,7 +22,7 @@ import type { TutorialState } from '@/lib/use-tutorial';
|
||||
import TutorialOverlay from '@/components/TutorialOverlay';
|
||||
import { GraduationCap } from 'lucide-react';
|
||||
|
||||
type WebappTab = 'cover' | 'handleiding' | 'dashboard' | 'invoer' | 'parameters' | 'clustering' | 'resultaten';
|
||||
type WebappTab = 'cover' | 'handleiding' | 'dashboard' | 'invoer' | 'bag' | 'parameters' | 'clustering' | 'resultaten';
|
||||
type HandleidingSubTab = 'handleiding' | 'casus';
|
||||
|
||||
const TICK_STYLE = { fontFamily: 'var(--font-ibm-plex-sans), sans-serif', fill: DMI.darkGray } as const;
|
||||
@@ -227,6 +230,7 @@ export default function WebappLayout({
|
||||
{ id: 'handleiding', label: 'Handleiding', icon: <BookOpen size={18} /> },
|
||||
{ id: 'dashboard', label: 'Cockpit', icon: <LayoutDashboard size={18} /> },
|
||||
{ id: 'invoer', label: 'Invoer', icon: <ClipboardList size={18} /> },
|
||||
{ id: 'bag', label: 'BAG-gebied', icon: <Map size={18} /> },
|
||||
{ id: 'parameters', label: 'Parameters', icon: <Settings size={18} /> },
|
||||
{ id: 'clustering', label: 'Clustering', icon: <Network size={18} /> },
|
||||
{ id: 'resultaten', label: 'Resultaten', icon: <BarChart3 size={18} /> },
|
||||
@@ -972,7 +976,19 @@ export default function WebappLayout({
|
||||
bepalen het verwachte verkeer en de bijbehorende ruimtebehoefte.
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '8px', flexShrink: 0 }}>
|
||||
<div style={{ display: 'flex', gap: '8px', flexShrink: 0, flexWrap: 'wrap' }}>
|
||||
<button
|
||||
onClick={() => setActiveTab('bag')}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: '6px',
|
||||
padding: '8px 14px', borderRadius: '6px', border: `1px solid ${DMI.darkBlue}`,
|
||||
backgroundColor: DMI.darkBlue, color: DMI.white,
|
||||
fontFamily: 'var(--font-ibm-plex-sans), sans-serif',
|
||||
fontWeight: 500, fontSize: '0.8rem', cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
<Map size={14} /> BAG-gebied inladen
|
||||
</button>
|
||||
<button
|
||||
data-tutorial="preset-gerard"
|
||||
onClick={state.resetToGerardDoustraat}
|
||||
@@ -1296,6 +1312,29 @@ export default function WebappLayout({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ---------------------------------------------------------- */}
|
||||
{/* BAG-GEBIED TAB */}
|
||||
{/* ---------------------------------------------------------- */}
|
||||
{activeTab === 'bag' && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
|
||||
<div>
|
||||
<h1 style={{ ...heading, fontSize: isMobile ? '1.2rem' : '1.5rem', marginBottom: '8px' }}>
|
||||
BAG-gebied inladen
|
||||
</h1>
|
||||
<p style={{ ...bodyText, fontSize: '0.9rem', maxWidth: '760px', lineHeight: 1.6 }}>
|
||||
Zoek een straat of teken een gebied op de kaart. Klik op <strong>BAG ophalen</strong> om
|
||||
verblijfsobjecten uit de PDOK BAG-service binnen het geselecteerde gebied te tellen.
|
||||
Met <strong>Overnemen</strong> worden aantallen en oppervlakten direct toegepast op de Invoer-tab.
|
||||
</p>
|
||||
</div>
|
||||
<BagPanel
|
||||
panelHeight="calc(100vh - 220px)"
|
||||
onApplied={() => setActiveTab('invoer')}
|
||||
/>
|
||||
<BagOsmDetails />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ---------------------------------------------------------- */}
|
||||
{/* PARAMETERS TAB */}
|
||||
{/* ---------------------------------------------------------- */}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useState, useCallback } from 'react';
|
||||
import { useSimulationState, type SimulationState, type LayoutType } from './use-simulation-state';
|
||||
import { useTutorial, type TutorialState } from './use-tutorial';
|
||||
|
||||
export interface AppContextValue {
|
||||
simulation: SimulationState;
|
||||
tutorial: TutorialState;
|
||||
layout: LayoutType;
|
||||
setLayout: (layout: LayoutType) => void;
|
||||
}
|
||||
|
||||
const AppContext = createContext<AppContextValue | null>(null);
|
||||
|
||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
const simulation = useSimulationState();
|
||||
const tutorial = useTutorial();
|
||||
const [layout, setLayoutState] = useState<LayoutType>('dmi');
|
||||
|
||||
const setLayout = useCallback(
|
||||
(next: LayoutType) => {
|
||||
if (tutorial.isActive) tutorial.stop();
|
||||
setLayoutState(next);
|
||||
},
|
||||
[tutorial]
|
||||
);
|
||||
|
||||
return (
|
||||
<AppContext.Provider value={{ simulation, tutorial, layout, setLayout }}>
|
||||
{children}
|
||||
</AppContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useApp(): AppContextValue {
|
||||
const ctx = useContext(AppContext);
|
||||
if (!ctx) throw new Error('useApp must be used within AppProvider');
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useState, useCallback } from 'react';
|
||||
import type { Feature, MultiPolygon, Polygon } from 'geojson';
|
||||
import type { BagQueryResult } from './bag-types';
|
||||
|
||||
export type BagPolygonFeature = Feature<Polygon | MultiPolygon>;
|
||||
|
||||
export interface BagContextValue {
|
||||
polygon: BagPolygonFeature | null;
|
||||
setPolygon: (poly: BagPolygonFeature | null) => void;
|
||||
queryResult: BagQueryResult | null;
|
||||
setQueryResult: (result: BagQueryResult | null) => void;
|
||||
isQuerying: boolean;
|
||||
setQuerying: (flag: boolean) => void;
|
||||
queryError: string | null;
|
||||
setQueryError: (err: string | null) => void;
|
||||
hasVisitedBagTab: boolean;
|
||||
markBagTabVisited: () => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
const BagContext = createContext<BagContextValue | null>(null);
|
||||
|
||||
export function BagProvider({ children }: { children: React.ReactNode }) {
|
||||
const [polygon, setPolygon] = useState<BagPolygonFeature | null>(null);
|
||||
const [queryResult, setQueryResult] = useState<BagQueryResult | null>(null);
|
||||
const [isQuerying, setQuerying] = useState(false);
|
||||
const [queryError, setQueryError] = useState<string | null>(null);
|
||||
const [hasVisitedBagTab, setHasVisitedBagTab] = useState(false);
|
||||
|
||||
const markBagTabVisited = useCallback(() => setHasVisitedBagTab(true), []);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setPolygon(null);
|
||||
setQueryResult(null);
|
||||
setQueryError(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<BagContext.Provider
|
||||
value={{
|
||||
polygon,
|
||||
setPolygon,
|
||||
queryResult,
|
||||
setQueryResult,
|
||||
isQuerying,
|
||||
setQuerying,
|
||||
queryError,
|
||||
setQueryError,
|
||||
hasVisitedBagTab,
|
||||
markBagTabVisited,
|
||||
reset,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</BagContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useBag(): BagContextValue {
|
||||
const ctx = useContext(BagContext);
|
||||
if (!ctx) throw new Error('useBag must be used within BagProvider');
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
House,
|
||||
ShoppingBag,
|
||||
Briefcase,
|
||||
Hotel,
|
||||
Users,
|
||||
Factory,
|
||||
HeartPulse,
|
||||
GraduationCap,
|
||||
Dumbbell,
|
||||
Lock,
|
||||
Circle,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import type { BagGebruiksdoel } from './bag-types';
|
||||
|
||||
export interface BagIconConfig {
|
||||
icon: LucideIcon;
|
||||
color: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export const BAG_ICONS: Record<BagGebruiksdoel, BagIconConfig> = {
|
||||
woonfunctie: { icon: House, color: '#0a3660', label: 'Wonen' },
|
||||
winkelfunctie: { icon: ShoppingBag, color: '#ff6b35', label: 'Winkel' },
|
||||
kantoorfunctie: { icon: Briefcase, color: '#115491', label: 'Kantoor' },
|
||||
logiesfunctie: { icon: Hotel, color: '#9b4f96', label: 'Logies' },
|
||||
bijeenkomstfunctie: { icon: Users, color: '#e1306c', label: 'Bijeenkomst' },
|
||||
industriefunctie: { icon: Factory, color: '#6c6c6c', label: 'Industrie' },
|
||||
gezondheidszorgfunctie: { icon: HeartPulse, color: '#d62828', label: 'Zorg' },
|
||||
onderwijsfunctie: { icon: GraduationCap, color: '#5a8f29', label: 'Onderwijs' },
|
||||
sportfunctie: { icon: Dumbbell, color: '#14a38b', label: 'Sport' },
|
||||
celfunctie: { icon: Lock, color: '#1a1a1a', label: 'Cel' },
|
||||
'overige gebruiksfunctie': { icon: Circle, color: '#999999', label: 'Overig' },
|
||||
};
|
||||
@@ -0,0 +1,169 @@
|
||||
import type {
|
||||
BagApplyPlan,
|
||||
BagBucket,
|
||||
BagGebruiksdoel,
|
||||
BagQueryResult,
|
||||
BagVboProperties,
|
||||
} from './bag-types';
|
||||
import type { Feature, Point } from 'geojson';
|
||||
import { FUNCTIONS } from './model-data';
|
||||
|
||||
const KANTOOR_KLEIN_MAX = 2500;
|
||||
const KANTOOR_MIDDEL_MAX = 10000;
|
||||
|
||||
const RETAIL_FOOD_SHOPS = new Set([
|
||||
'bakery',
|
||||
'butcher',
|
||||
'cheese',
|
||||
'seafood',
|
||||
'deli',
|
||||
'greengrocer',
|
||||
'pastry',
|
||||
'confectionery',
|
||||
'wine',
|
||||
'beverages',
|
||||
'chocolate',
|
||||
'tea',
|
||||
'coffee',
|
||||
'farm',
|
||||
'dairy',
|
||||
]);
|
||||
|
||||
const SUPERMARKT_SHOPS = new Set(['supermarket', 'convenience']);
|
||||
|
||||
const FUNC_NAME: Record<string, string> = Object.fromEntries(FUNCTIONS.map((f) => [f.id, f.name]));
|
||||
|
||||
function applyBucket(
|
||||
plan: BagApplyPlan,
|
||||
funcId: string,
|
||||
count: number,
|
||||
totalBvo: number,
|
||||
gebruiksdoel: BagGebruiksdoel
|
||||
): void {
|
||||
if (count <= 0) return;
|
||||
plan.functionCounts[funcId] = (plan.functionCounts[funcId] ?? 0) + count;
|
||||
plan.functionBvo[funcId] = Math.round((plan.functionBvo[funcId] ?? 0) + totalBvo);
|
||||
plan.functionInputMode[funcId] = 'bvo';
|
||||
const totalC = plan.functionCounts[funcId];
|
||||
const totalB = plan.functionBvo[funcId];
|
||||
plan.bvoPerUnit[funcId] = Math.max(1, Math.round(totalB / Math.max(1, totalC)));
|
||||
plan.mapping.push({
|
||||
from: gebruiksdoel,
|
||||
toFuncId: funcId,
|
||||
toFuncName: FUNC_NAME[funcId] ?? funcId,
|
||||
count,
|
||||
totalBvo: Math.round(totalBvo),
|
||||
});
|
||||
}
|
||||
|
||||
function splitKantoor(bucket: BagBucket): { klein: BagBucket; middel: BagBucket; groot: BagBucket } {
|
||||
const klein: BagBucket = { gebruiksdoel: 'kantoorfunctie', count: 0, totalOppervlakte: 0, oppervlakten: [] };
|
||||
const middel: BagBucket = { gebruiksdoel: 'kantoorfunctie', count: 0, totalOppervlakte: 0, oppervlakten: [] };
|
||||
const groot: BagBucket = { gebruiksdoel: 'kantoorfunctie', count: 0, totalOppervlakte: 0, oppervlakten: [] };
|
||||
for (const opp of bucket.oppervlakten) {
|
||||
const target = opp <= KANTOOR_KLEIN_MAX ? klein : opp <= KANTOOR_MIDDEL_MAX ? middel : groot;
|
||||
target.count += 1;
|
||||
target.totalOppervlakte += opp;
|
||||
target.oppervlakten.push(opp);
|
||||
}
|
||||
return { klein, middel, groot };
|
||||
}
|
||||
|
||||
interface SubBucket {
|
||||
count: number;
|
||||
totalBvo: number;
|
||||
}
|
||||
|
||||
export function classifyWinkel(props: BagVboProperties): 'F2' | 'F3' | 'F4' | 'F5' {
|
||||
const osm = props.osm;
|
||||
if (osm?.shop && SUPERMARKT_SHOPS.has(osm.shop)) return 'F2';
|
||||
if (osm?.shop && RETAIL_FOOD_SHOPS.has(osm.shop)) return 'F3';
|
||||
if (osm?.brand) return 'F4';
|
||||
return 'F5';
|
||||
}
|
||||
|
||||
export function classifyHoreca(props: BagVboProperties): 'F6' | 'F7' | 'F8' {
|
||||
const osm = props.osm;
|
||||
const a = osm?.amenity;
|
||||
if (a === 'cafe' || a === 'bar' || a === 'pub' || a === 'biergarten') return 'F8';
|
||||
if (a === 'fast_food') return 'F7';
|
||||
if (a === 'restaurant') {
|
||||
const cuisine = (osm?.cuisine ?? '').toLowerCase();
|
||||
if (cuisine === 'fine_dining') return 'F6';
|
||||
return 'F7';
|
||||
}
|
||||
return 'F7';
|
||||
}
|
||||
|
||||
function splitByOsm(
|
||||
features: Feature<Point, BagVboProperties>[],
|
||||
gebruiksdoel: 'winkelfunctie' | 'bijeenkomstfunctie'
|
||||
): Record<string, SubBucket> {
|
||||
const out: Record<string, SubBucket> = {};
|
||||
for (const f of features) {
|
||||
if (f.properties.gebruiksdoel !== gebruiksdoel) continue;
|
||||
const target =
|
||||
gebruiksdoel === 'winkelfunctie'
|
||||
? classifyWinkel(f.properties)
|
||||
: classifyHoreca(f.properties);
|
||||
if (!out[target]) out[target] = { count: 0, totalBvo: 0 };
|
||||
out[target].count += 1;
|
||||
out[target].totalBvo += f.properties.oppervlakte;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mapBagToApplyPlan(result: BagQueryResult): BagApplyPlan {
|
||||
const plan: BagApplyPlan = {
|
||||
functionCounts: {},
|
||||
functionBvo: {},
|
||||
functionInputMode: {},
|
||||
bvoPerUnit: {},
|
||||
mapping: [],
|
||||
unmappedBuckets: [],
|
||||
};
|
||||
|
||||
const woon = result.buckets.woonfunctie;
|
||||
if (woon) applyBucket(plan, 'F1', woon.count, woon.totalOppervlakte, 'woonfunctie');
|
||||
|
||||
if (result.buckets.winkelfunctie) {
|
||||
const split = splitByOsm(result.features.features, 'winkelfunctie');
|
||||
for (const [funcId, sub] of Object.entries(split)) {
|
||||
applyBucket(plan, funcId, sub.count, sub.totalBvo, 'winkelfunctie');
|
||||
}
|
||||
}
|
||||
|
||||
const logies = result.buckets.logiesfunctie;
|
||||
if (logies) applyBucket(plan, 'F9', logies.count, logies.totalOppervlakte, 'logiesfunctie');
|
||||
|
||||
if (result.buckets.bijeenkomstfunctie) {
|
||||
const split = splitByOsm(result.features.features, 'bijeenkomstfunctie');
|
||||
for (const [funcId, sub] of Object.entries(split)) {
|
||||
applyBucket(plan, funcId, sub.count, sub.totalBvo, 'bijeenkomstfunctie');
|
||||
}
|
||||
}
|
||||
|
||||
const kantoor = result.buckets.kantoorfunctie;
|
||||
if (kantoor) {
|
||||
const { klein, middel, groot } = splitKantoor(kantoor);
|
||||
applyBucket(plan, 'F10', klein.count, klein.totalOppervlakte, 'kantoorfunctie');
|
||||
applyBucket(plan, 'F11', middel.count, middel.totalOppervlakte, 'kantoorfunctie');
|
||||
applyBucket(plan, 'F12', groot.count, groot.totalOppervlakte, 'kantoorfunctie');
|
||||
}
|
||||
|
||||
const mappedKeys: BagGebruiksdoel[] = [
|
||||
'woonfunctie',
|
||||
'winkelfunctie',
|
||||
'logiesfunctie',
|
||||
'kantoorfunctie',
|
||||
'bijeenkomstfunctie',
|
||||
];
|
||||
for (const [key, bucket] of Object.entries(result.buckets)) {
|
||||
if (!bucket) continue;
|
||||
if (!mappedKeys.includes(key as BagGebruiksdoel) && bucket.count > 0) {
|
||||
plan.unmappedBuckets.push(bucket);
|
||||
}
|
||||
}
|
||||
|
||||
return plan;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { Feature, FeatureCollection, MultiPolygon, Point, Polygon } from 'geojson';
|
||||
|
||||
export type BagGebruiksdoel =
|
||||
| 'woonfunctie'
|
||||
| 'winkelfunctie'
|
||||
| 'kantoorfunctie'
|
||||
| 'logiesfunctie'
|
||||
| 'bijeenkomstfunctie'
|
||||
| 'industriefunctie'
|
||||
| 'gezondheidszorgfunctie'
|
||||
| 'onderwijsfunctie'
|
||||
| 'sportfunctie'
|
||||
| 'celfunctie'
|
||||
| 'overige gebruiksfunctie';
|
||||
|
||||
export const BAG_GEBRUIKSDOELEN: BagGebruiksdoel[] = [
|
||||
'woonfunctie',
|
||||
'winkelfunctie',
|
||||
'kantoorfunctie',
|
||||
'logiesfunctie',
|
||||
'bijeenkomstfunctie',
|
||||
'industriefunctie',
|
||||
'gezondheidszorgfunctie',
|
||||
'onderwijsfunctie',
|
||||
'sportfunctie',
|
||||
'celfunctie',
|
||||
'overige gebruiksfunctie',
|
||||
];
|
||||
|
||||
export interface BagBucket {
|
||||
gebruiksdoel: BagGebruiksdoel;
|
||||
count: number;
|
||||
totalOppervlakte: number;
|
||||
oppervlakten: number[];
|
||||
}
|
||||
|
||||
export interface BagVboOsmTags {
|
||||
shop?: string;
|
||||
amenity?: string;
|
||||
brand?: string;
|
||||
name?: string;
|
||||
cuisine?: string;
|
||||
}
|
||||
|
||||
export interface BagVboProperties {
|
||||
id?: string;
|
||||
gebruiksdoel: BagGebruiksdoel;
|
||||
oppervlakte: number;
|
||||
osm?: BagVboOsmTags;
|
||||
}
|
||||
|
||||
export interface BagQueryResult {
|
||||
totalVerblijfsobjecten: number;
|
||||
buckets: Partial<Record<BagGebruiksdoel, BagBucket>>;
|
||||
polygon: Feature<Polygon | MultiPolygon>;
|
||||
features: FeatureCollection<Point, BagVboProperties>;
|
||||
queriedAt: string;
|
||||
truncated: boolean;
|
||||
multiUseCount: number;
|
||||
}
|
||||
|
||||
export interface BagMappingEntry {
|
||||
from: BagGebruiksdoel;
|
||||
toFuncId: string;
|
||||
toFuncName: string;
|
||||
count: number;
|
||||
totalBvo: number;
|
||||
}
|
||||
|
||||
export interface BagApplyPlan {
|
||||
functionCounts: Record<string, number>;
|
||||
functionBvo: Record<string, number>;
|
||||
functionInputMode: Record<string, 'count' | 'bvo'>;
|
||||
bvoPerUnit: Record<string, number>;
|
||||
mapping: BagMappingEntry[];
|
||||
unmappedBuckets: BagBucket[];
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
export interface OsmPoi {
|
||||
lon: number;
|
||||
lat: number;
|
||||
shop?: string;
|
||||
amenity?: string;
|
||||
brand?: string;
|
||||
name?: string;
|
||||
cuisine?: string;
|
||||
}
|
||||
|
||||
const OVERPASS_URL = 'https://overpass-api.de/api/interpreter';
|
||||
const HORECA_AMENITIES = ['restaurant', 'cafe', 'bar', 'fast_food', 'pub', 'biergarten'];
|
||||
|
||||
export async function fetchOsmPois(bbox: [number, number, number, number]): Promise<OsmPoi[]> {
|
||||
const [minX, minY, maxX, maxY] = bbox;
|
||||
const ovBbox = `${minY},${minX},${maxY},${maxX}`;
|
||||
const amenityRegex = HORECA_AMENITIES.join('|');
|
||||
const query = `
|
||||
[out:json][timeout:25];
|
||||
(
|
||||
node["shop"](${ovBbox});
|
||||
node["amenity"~"^(${amenityRegex})$"](${ovBbox});
|
||||
way["shop"](${ovBbox});
|
||||
way["amenity"~"^(${amenityRegex})$"](${ovBbox});
|
||||
);
|
||||
out tags center;`;
|
||||
|
||||
const resp = await fetch(OVERPASS_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'User-Agent': 'ruimtemodel-stadslogistiek/0.1 (https://github.com/robbertj85/modelruimte)',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: 'data=' + encodeURIComponent(query),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`Overpass returned ${resp.status}`);
|
||||
|
||||
const data = (await resp.json()) as {
|
||||
elements?: Array<{
|
||||
type: string;
|
||||
lat?: number;
|
||||
lon?: number;
|
||||
center?: { lat: number; lon: number };
|
||||
tags?: Record<string, string>;
|
||||
}>;
|
||||
};
|
||||
|
||||
const pois: OsmPoi[] = [];
|
||||
for (const el of data.elements ?? []) {
|
||||
const lon = el.type === 'node' ? el.lon : el.center?.lon;
|
||||
const lat = el.type === 'node' ? el.lat : el.center?.lat;
|
||||
if (typeof lon !== 'number' || typeof lat !== 'number') continue;
|
||||
pois.push({
|
||||
lon,
|
||||
lat,
|
||||
shop: el.tags?.shop,
|
||||
amenity: el.tags?.amenity,
|
||||
brand: el.tags?.brand,
|
||||
name: el.tags?.name,
|
||||
cuisine: el.tags?.cuisine,
|
||||
});
|
||||
}
|
||||
return pois;
|
||||
}
|
||||
|
||||
export function findNearestOsm(
|
||||
pt: [number, number],
|
||||
pois: OsmPoi[],
|
||||
maxMeters = 25,
|
||||
filter?: (poi: OsmPoi) => boolean
|
||||
): OsmPoi | null {
|
||||
let best: OsmPoi | null = null;
|
||||
let bestD = Infinity;
|
||||
for (const p of pois) {
|
||||
if (filter && !filter(p)) continue;
|
||||
const d = haversineMeters(pt, [p.lon, p.lat]);
|
||||
if (d < bestD && d <= maxMeters) {
|
||||
bestD = d;
|
||||
best = p;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
const HORECA_AMENITY_SET = new Set(HORECA_AMENITIES);
|
||||
|
||||
export function isShopPoi(p: OsmPoi): boolean {
|
||||
return Boolean(p.shop) && p.shop !== 'vacant';
|
||||
}
|
||||
|
||||
export function isHorecaPoi(p: OsmPoi): boolean {
|
||||
return Boolean(p.amenity && HORECA_AMENITY_SET.has(p.amenity));
|
||||
}
|
||||
|
||||
function haversineMeters(a: [number, number], b: [number, number]): number {
|
||||
const R = 6371000;
|
||||
const toRad = (d: number) => (d * Math.PI) / 180;
|
||||
const dLat = toRad(b[1] - a[1]);
|
||||
const dLon = toRad(b[0] - a[0]);
|
||||
const lat1 = toRad(a[1]);
|
||||
const lat2 = toRad(b[1]);
|
||||
const x =
|
||||
Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
|
||||
return 2 * R * Math.asin(Math.sqrt(x));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { AppProvider } from './app-context';
|
||||
import { BagProvider } from './bag-context';
|
||||
|
||||
export function Providers({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<AppProvider>
|
||||
<BagProvider>{children}</BagProvider>
|
||||
</AppProvider>
|
||||
);
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
type FunctionDef,
|
||||
type DistributionDef,
|
||||
} from '@/lib/simulation';
|
||||
import type { BagApplyPlan } from '@/lib/bag-types';
|
||||
|
||||
export type LayoutType = 'dmi' | 'webapp';
|
||||
|
||||
@@ -95,6 +96,7 @@ export interface SimulationState {
|
||||
handleCustomVehicleNameChange: (vehicleId: string, name: string) => void;
|
||||
handleCustomDistributionNameChange: (distId: string, name: string) => void;
|
||||
handleEnsureProfile: (profileKey: string, numVehicles: number) => void;
|
||||
handleApplyBagPlan: (plan: BagApplyPlan) => void;
|
||||
}
|
||||
|
||||
function getUniqueClusterIds(assignments: Record<string, number>): number[] {
|
||||
@@ -552,6 +554,13 @@ export function useSimulationState(): SimulationState {
|
||||
setCustomDistributions((prev) => prev.map((d) => (d.id === distId ? { ...d, name } : d)));
|
||||
}, []);
|
||||
|
||||
const handleApplyBagPlan = useCallback((plan: BagApplyPlan) => {
|
||||
setFunctionCounts((prev) => ({ ...prev, ...plan.functionCounts }));
|
||||
setFunctionBvo((prev) => ({ ...prev, ...plan.functionBvo }));
|
||||
setFunctionInputMode((prev) => ({ ...prev, ...plan.functionInputMode }));
|
||||
setBvoPerUnit((prev) => ({ ...prev, ...plan.bvoPerUnit }));
|
||||
}, []);
|
||||
|
||||
const handleEnsureProfile = useCallback((profileKey: string, numVehicles: number) => {
|
||||
setDeliveryProfiles((prev) => {
|
||||
if (prev[profileKey]) return prev;
|
||||
@@ -620,5 +629,6 @@ export function useSimulationState(): SimulationState {
|
||||
handleCustomVehicleNameChange,
|
||||
handleCustomDistributionNameChange,
|
||||
handleEnsureProfile,
|
||||
handleApplyBagPlan,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import type {
|
||||
LineString,
|
||||
MultiLineString,
|
||||
MultiPolygon,
|
||||
Point,
|
||||
Polygon,
|
||||
Position,
|
||||
} from 'geojson';
|
||||
|
||||
function parseRing(ring: string): Position[] {
|
||||
return ring.split(',').map((pair) => {
|
||||
const [x, y] = pair.trim().split(/\s+/).map(Number);
|
||||
return [x, y] as Position;
|
||||
});
|
||||
}
|
||||
|
||||
export function wktToGeoJSON(
|
||||
wkt: string
|
||||
): Point | LineString | MultiLineString | Polygon | MultiPolygon | null {
|
||||
const trimmed = wkt.trim();
|
||||
if (trimmed.startsWith('POINT')) {
|
||||
const inner = trimmed.replace(/^POINT\s*\(/, '').replace(/\)$/, '').trim();
|
||||
const [x, y] = inner.split(/\s+/).map(Number);
|
||||
if (Number.isNaN(x) || Number.isNaN(y)) return null;
|
||||
return { type: 'Point', coordinates: [x, y] };
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('LINESTRING')) {
|
||||
const inner = trimmed.replace(/^LINESTRING\s*\(/, '').replace(/\)$/, '');
|
||||
return { type: 'LineString', coordinates: parseRing(inner) };
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('MULTILINESTRING')) {
|
||||
const body = trimmed.replace(/^MULTILINESTRING\s*\(/, '').replace(/\)$/, '');
|
||||
const lines = body.split(/\)\s*,\s*\(/).map((l) => l.replace(/^\(/, '').replace(/\)$/, ''));
|
||||
return { type: 'MultiLineString', coordinates: lines.map(parseRing) };
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('POLYGON')) {
|
||||
const body = trimmed.replace(/^POLYGON\s*\(/, '').replace(/\)$/, '');
|
||||
const rings = body
|
||||
.split(/\)\s*,\s*\(/)
|
||||
.map((r) => r.replace(/^\(/, '').replace(/\)$/, ''))
|
||||
.map(parseRing);
|
||||
return { type: 'Polygon', coordinates: rings };
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('MULTIPOLYGON')) {
|
||||
const body = trimmed.replace(/^MULTIPOLYGON\s*\(\s*/, '').replace(/\s*\)$/, '');
|
||||
const polygonStrings = body.split(/\)\s*\)\s*,\s*\(\s*\(/);
|
||||
const polygons = polygonStrings.map((polyStr, idx) => {
|
||||
let p = polyStr;
|
||||
if (idx === 0) p = p.replace(/^\(\(/, '').replace(/^\(/, '');
|
||||
if (idx === polygonStrings.length - 1) p = p.replace(/\)\)$/, '').replace(/\)$/, '');
|
||||
const rings = p.split(/\)\s*,\s*\(/).map(parseRing);
|
||||
return rings;
|
||||
});
|
||||
return { type: 'MultiPolygon', coordinates: polygons };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user