Repository Public
1// UQO Éval — Métré : sélecteur de vue satellite (Mapbox GL) pour créer un plan de site géoréférencé — adresse, MAMH ou déplacement libre.2"use client";3import { useEffect, useRef, useState } from "react";4import mapboxgl from "mapbox-gl";5import "mapbox-gl/dist/mapbox-gl.css";6import { MAPBOX_TOKEN } from "@/lib/kamaps";7import { api, Btn, Err, Input } from "./ui";89export default function MapPicker({ fr, initial, onCapture, onCancel }: { fr: boolean; initial: { lat: number; lng: number; q?: string | null; mamh?: string | null }; onCapture: (v: { lat: number; lng: number; zoom: number; label: string; style: string }) => Promise<void>; onCancel: () => void }) {10 const ref = useRef<HTMLDivElement>(null);11 const mapRef = useRef<mapboxgl.Map | null>(null);12 const [q, setQ] = useState(initial.q ?? "");13 const [res, setRes] = useState<{ name: string; lat: number; lng: number; source: string }[]>([]);14 const [view, setView] = useState({ lat: initial.lat, lng: initial.lng, zoom: 18.5 });15 const [style, setStyle] = useState<"satellite" | "streets">("satellite");16 const [label, setLabel] = useState("Site");17 const [busy, setBusy] = useState(false); const [err, setErr] = useState<string | null>(null);18 useEffect(() => {19 if (!ref.current || mapRef.current) return;20 mapboxgl.accessToken = MAPBOX_TOKEN;21 const m = new mapboxgl.Map({ container: ref.current, style: "mapbox://styles/mapbox/satellite-streets-v12", center: [initial.lng, initial.lat], zoom: 18.5, pitch: 0, bearing: 0, attributionControl: true });22 m.addControl(new mapboxgl.NavigationControl({ showCompass: false }), "top-right");23 m.addControl(new mapboxgl.ScaleControl({ unit: "metric" }), "bottom-left");24 m.on("moveend", () => { const c = m.getCenter(); setView({ lat: c.lat, lng: c.lng, zoom: m.getZoom() }); });25 mapRef.current = m;26 return () => { m.remove(); mapRef.current = null; };27 }, [initial.lat, initial.lng]);28 useEffect(() => { mapRef.current?.setStyle(style === "satellite" ? "mapbox://styles/mapbox/satellite-streets-v12" : "mapbox://styles/mapbox/streets-v12"); }, [style]);29 useEffect(() => { if (initial.mamh) api<{ results: typeof res }>(`/geocode?mamh=${encodeURIComponent(initial.mamh)}`).then((r) => { if (r.results[0]) mapRef.current?.flyTo({ center: [r.results[0].lng, r.results[0].lat], zoom: 18.5 }); }).catch(() => undefined); }, [initial.mamh]);30 const search = async () => { setErr(null); try { const r = await api<{ results: typeof res }>(`/geocode?q=${encodeURIComponent(q)}`); setRes(r.results); if (r.results[0]) mapRef.current?.flyTo({ center: [r.results[0].lng, r.results[0].lat], zoom: 18.5 }); } catch (e) { setErr((e as Error).message); } };31 const zoom = Math.min(20, Math.max(14, Math.round(view.zoom)));32 const mPerPx = (40075016.686 * Math.cos((view.lat * Math.PI) / 180)) / (512 * Math.pow(2, zoom)) / 2;33 return (34 <div className="space-y-3">35 <div className="flex flex-wrap items-end gap-2">36 <div className="min-w-[260px] flex-1"><Input value={q} onChange={(e) => setQ(e.target.value)} placeholder={fr ? "Adresse (ex. 283 boul. Alexandre-Taché, Gatineau)" : "Address"} onKeyDown={(e) => { if (e.key === "Enter") void search(); }} /></div>37 <Btn small onClick={() => void search()}>{fr ? "Chercher" : "Search"}</Btn>38 <select value={style} onChange={(e) => setStyle(e.target.value as "satellite" | "streets")} className="vp-input !min-h-0 w-[140px] text-[12px]"><option value="satellite">{fr ? "Satellite" : "Satellite"}</option><option value="streets">{fr ? "Plan de rues" : "Streets"}</option></select>39 <Input value={label} onChange={(e) => setLabel(e.target.value)} className="!min-h-0 w-[140px] text-[12px]" placeholder={fr ? "nom de la page" : "page name"} />40 </div>41 {res.length > 1 && <div className="flex flex-wrap gap-1">{res.map((r) => <button key={r.name} type="button" className="chip vp-mono text-[10.5px] border border-[var(--line)] rounded-full px-2 py-0.5" onClick={() => mapRef.current?.flyTo({ center: [r.lng, r.lat], zoom: 18.5 })}>{r.name}</button>)}</div>}42 <div ref={ref} style={{ height: 420, borderRadius: 8, overflow: "hidden", border: "1px solid #d9dee2" }} />43 <div className="flex flex-wrap items-center justify-between gap-2">44 <span className="vp-mono text-[11px] text-ink-2">{view.lat.toFixed(6)}, {view.lng.toFixed(6)} · zoom {zoom} · {(mPerPx * 100).toFixed(1)} cm/px · {fr ? "image 2 560 × 1 920 px ≈" : "image 2,560 × 1,920 px ≈"} {Math.round(2560 * mPerPx)} × {Math.round(1920 * mPerPx)} m</span>45 <span className="flex gap-2"><Btn small onClick={onCancel}>{fr ? "Annuler" : "Cancel"}</Btn><Btn small tone="primary" disabled={busy} onClick={async () => { setBusy(true); setErr(null); try { await onCapture({ lat: view.lat, lng: view.lng, zoom, label, style }); } catch (e) { setErr((e as Error).message); } finally { setBusy(false); } }}>{busy ? "…" : fr ? "Capturer cette vue → plan de site" : "Capture this view → site plan"}</Btn></span>46 </div>47 <p className="text-[11.5px] text-ink-3">{fr ? "Cadrez la propriété (zoom 18–20 pour un lot résidentiel). L'image est géoréférencée : l'échelle est calculée exactement depuis la projection ; vous tracez ensuite le lot, l'empreinte, l'entrée, la terrasse… directement sur l'image. © Mapbox © OpenStreetMap © Maxar." : "Frame the property (zoom 18–20 for a residential lot). The image is georeferenced: the scale is computed exactly from the projection; you then trace the lot, footprint, driveway, deck… directly on the image. © Mapbox © OpenStreetMap © Maxar."}</p>48 <Err msg={err} />49 </div>50 );51}52