import React, { useEffect, useRef } from 'react'; import L from 'leaflet'; import 'leaflet/dist/leaflet.css'; // Fix for default marker icon in Leaflet with Next.js if (typeof window !== 'undefined') { const DefaultIcon = L.icon({ iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png', shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12, 41], }); L.Marker.prototype.options.icon = DefaultIcon; } interface LeafletMapProps { address: string; lat: number; lng: number; } export default function LeafletMap({ address, lat, lng }: LeafletMapProps) { const mapRef = useRef(null); const mapInstanceRef = useRef(null); useEffect(() => { if (!mapRef.current || mapInstanceRef.current) return; // Initialize map const map = L.map(mapRef.current, { center: [lat, lng], zoom: 15, scrollWheelZoom: false, }); // Add tiles L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors', }).addTo(map); // Add marker const marker = L.marker([lat, lng]).addTo(map); // Create popup content const popupContent = `
KLZ Cables
${address.replace(/\n/g, '
')}
`; marker.bindPopup(popupContent); mapInstanceRef.current = map; // Cleanup on unmount return () => { if (mapInstanceRef.current) { mapInstanceRef.current.remove(); mapInstanceRef.current = null; } }; }, [lat, lng, address]); return
; }