Files
nav-carte/components/NavMapV2.vue
T
2026-10-02 17:57:27 +02:00

276 lines
8.6 KiB
Vue

<template>
<div class="relative w-full h-full">
<div ref="mapContainer" class="w-full h-full rounded-none" />
</div>
</template>
<script setup lang="ts">
const baseTiles = useBaseTiles()
import type { Map, Marker, DivIcon } from 'leaflet'
import type { StructureV2 } from '~/types/structure-v2'
// Couleurs par famille (synchronisées avec v2-bifurcation.css)
const FAMILLE_COLORS: Record<number, string> = {
1: '#a85d3e',
2: '#c4a472',
3: '#d4a017',
4: '#5a7a4a',
5: '#3d6a8c',
}
const props = defineProps<{
structures: StructureV2[]
selectedId?: string | null
/** Fiche survolée dans la liste (B11) : épingle cerclée de safran, sans recentrer. */
survolId?: string | null
}>()
const emit = defineEmits<{
'select-structure': [id: string]
/** Survol d'une épingle (B11) : la liste allume la carte-fiche. */
survol: [id: string | null]
}>()
const mapContainer = ref<HTMLElement | null>(null)
let mapInstance: Map | null = null
let clusterGroup: any = null
const markers = new Map<string, Marker>()
let tileLayerInstance: any = null
let resizeObserver: ResizeObserver | null = null
function getFamilleColor(famille: number): string {
return FAMILLE_COLORS[famille] ?? '#888888'
}
function createPinIcon(famille: number, isSelected = false, isSurvol = false): DivIcon {
const L = (window as any).L
const bg = getFamilleColor(famille)
const size = isSelected || isSurvol ? 20 : 14
const border = isSurvol ? '#f5b342' : isSelected ? 'white' : 'rgba(255,255,255,0.7)'
const shadow = isSurvol ? '0 0 0 4px rgba(245,179,66,0.6)' : isSelected ? `0 0 0 4px ${bg}55` : 'none'
return L.divIcon({
className: '',
html: `<div style="
width: ${size}px;
height: ${size}px;
border-radius: 50%;
background: ${bg};
border: 2px solid ${border};
box-shadow: ${shadow};
transition: all 0.2s;
"></div>`,
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
popupAnchor: [0, -(size / 2 + 4)],
})
}
async function initMap() {
if (!mapContainer.value) return
const Lmod = await import('leaflet')
const L: any = (Lmod as any).default || Lmod
await import('leaflet/dist/leaflet.css')
// @ts-ignore
await import('leaflet.markercluster/dist/MarkerCluster.css')
// @ts-ignore
await import('leaflet.markercluster/dist/MarkerCluster.Default.css')
// Installer L globalement AVANT le plugin
;(window as any).L = L
// @ts-ignore
await import('leaflet.markercluster')
if (!mapContainer.value?.isConnected) return // page quittée pendant le chargement (ex. ?random=1)
const MarkerClusterGroup = L.MarkerClusterGroup
mapInstance = L.map(mapContainer.value, {
center: [46.6, 2.3],
zoom: 5,
zoomControl: true,
attributionControl: true,
minZoom: 2,
maxZoom: 18,
})
const isDark = typeof document !== 'undefined' && document.documentElement.classList.contains('dark')
const tileUrl = baseTiles.url(isDark)
tileLayerInstance = L.tileLayer(tileUrl, {
attribution: baseTiles.attribution,
maxZoom: 19,
})
tileLayerInstance.addTo(mapInstance!)
clusterGroup = new MarkerClusterGroup({
disableClusteringAtZoom: 14,
maxClusterRadius: 50,
showCoverageOnHover: false,
iconCreateFunction: (cluster: any) => {
const count = cluster.getChildCount()
return L.divIcon({
html: `<div style="
width: 36px; height: 36px; border-radius: 50%;
background: var(--nav-primary);
color: var(--nav-text-on-primary);
display: flex; align-items: center; justify-content: center;
font-weight: 700; font-size: 13px;
border: 2px solid white;
font-family: var(--nav-font);
">${count}</div>`,
className: '',
iconSize: [36, 36],
iconAnchor: [18, 18],
})
},
})
mapInstance.addLayer(clusterGroup)
updateMarkers(L)
// B11 : la carte change de largeur sans que la fenêtre bouge (Mixte ↔ Carte ↔ Fiches)
resizeObserver = new ResizeObserver(() => mapInstance?.invalidateSize({ pan: false }))
resizeObserver.observe(mapContainer.value)
}
function iconeDe(s: StructureV2): DivIcon {
return createPinIcon(s.famille_principale, s.id === props.selectedId, s.id === props.survolId)
}
function updateMarkers(L?: any) {
if (!mapInstance || !clusterGroup) return
const leaflet = L || (window as any).L
if (!leaflet) return
clusterGroup.clearLayers()
markers.clear()
const structuresWithCoords = props.structures.filter(
(s) => s.latitude != null && s.longitude != null
)
structuresWithCoords.forEach((structure) => {
const marker = leaflet.marker([structure.latitude!, structure.longitude!], { icon: iconeDe(structure), title: structure.nom })
const hashtagsHtml = structure.hashtags.slice(0, 2)
.map(h => `<span style="font-size:10px;color:var(--nav-text-muted);">${h}</span>`)
.join(' ')
marker.bindPopup(`
<div style="font-family: var(--nav-font); min-width: 190px; padding: 4px 0;">
<div style="font-weight: 700; color: var(--nav-text); margin-bottom: 2px; font-size: 0.9rem;">${structure.nom}</div>
<div style="font-size: 11px; color: var(--nav-text-muted); margin-bottom: 4px;">${structure.type_principal} · ${structure.ville}, ${structure.pays}</div>
${hashtagsHtml ? `<div style="margin-bottom: 6px;">${hashtagsHtml}</div>` : ''}
<div style="font-size: 11px; color: var(--nav-text); line-height: 1.4; margin-bottom: 8px;">${structure.description_courte.slice(0, 100)}…</div>
<button onclick="document.dispatchEvent(new CustomEvent('nav-v2-select', {detail:'${structure.id}'}))" style="
font-size: 12px;
color: var(--nav-primary-solid);
text-decoration: underline;
background: none;
border: none;
cursor: pointer;
padding: 0;
font-family: var(--nav-font);
">Voir la fiche →</button>
</div>
`, { maxWidth: 260 })
marker.on('click', () => emit('select-structure', structure.id))
marker.on('mouseover', () => emit('survol', structure.id))
marker.on('mouseout', () => emit('survol', null))
markers.set(structure.id, marker)
clusterGroup.addLayer(marker)
})
}
// Ecouter l'event custom depuis les popups Leaflet
function onNavV2Select(e: CustomEvent) {
emit('select-structure', e.detail)
}
watch(
() => props.structures,
() => updateMarkers(),
{ deep: false }
)
watch(
() => props.selectedId,
(newId, oldId) => {
if (!mapInstance) return
const leaflet = (window as any).L
if (!leaflet) return
if (oldId != null) {
const oldMarker = markers.get(oldId)
const oldStructure = props.structures.find(s => s.id === oldId)
if (oldMarker && oldStructure) {
oldMarker.setIcon(iconeDe(oldStructure))
}
}
if (newId != null) {
const newMarker = markers.get(newId)
const newStructure = props.structures.find(s => s.id === newId)
if (newMarker && newStructure) {
newMarker.setIcon(iconeDe(newStructure))
const latLng = newMarker.getLatLng()
mapInstance.panTo(latLng, { animate: true })
}
}
}
)
// Survol depuis la liste : épingle cerclée de safran, sans recentrer la carte
watch(
() => props.survolId,
(newId, oldId) => {
for (const id of [oldId, newId]) {
if (id == null) continue
const m = markers.get(id)
const s = props.structures.find(x => x.id === id)
if (m && s) m.setIcon(iconeDe(s))
allumerCluster(m, id === newId)
}
}
)
// Épingle regroupée dans un cluster : c'est le cluster visible qui s'allume
function allumerCluster(m: Marker | undefined, on: boolean) {
const parent = m && clusterGroup?.getVisibleParent(m)
const el = parent && parent !== m ? (parent as any)._icon?.firstElementChild as HTMLElement | undefined : undefined
if (el) el.style.boxShadow = on ? '0 0 0 4px #f5b342' : ''
}
function updateTileTheme(dark: boolean) {
if (!mapInstance || !tileLayerInstance) return
const L = (window as any).L
if (!L) return
const url = baseTiles.url(dark)
tileLayerInstance.setUrl(url)
}
let themeObserver: MutationObserver | null = null
onMounted(() => {
initMap()
document.addEventListener('nav-v2-select', onNavV2Select as EventListener)
themeObserver = new MutationObserver(() => {
const dark = document.documentElement.classList.contains('dark')
updateTileTheme(dark)
})
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] })
})
onUnmounted(() => {
document.removeEventListener('nav-v2-select', onNavV2Select as EventListener)
themeObserver?.disconnect()
resizeObserver?.disconnect()
if (mapInstance) {
mapInstance.remove()
mapInstance = null
}
})
</script>