diff --git a/client/src/pages/MapView.jsx b/client/src/pages/MapView.jsx index a6c5981..f9053d4 100644 --- a/client/src/pages/MapView.jsx +++ b/client/src/pages/MapView.jsx @@ -25,17 +25,19 @@ Icon.Default.mergeOptions({ shadowUrl, }); -// Component to handle dynamic map bounds - only on initial load +// Component to handle initial map bounds - ONLY runs once on first load const FitBounds = ({ bounds, shouldFit }) => { const map = useMap(); + const [hasRun, setHasRun] = useState(false); useEffect(() => { - console.log('FitBounds: useEffect triggered - bounds:', bounds, 'shouldFit:', shouldFit); - if (bounds && bounds.length === 2 && shouldFit) { - console.log('FitBounds: Calling map.fitBounds with bounds:', bounds); + console.log('FitBounds: useEffect triggered - bounds:', bounds, 'shouldFit:', shouldFit, 'hasRun:', hasRun); + if (bounds && bounds.length === 2 && shouldFit && !hasRun) { + console.log('FitBounds: Calling map.fitBounds ONCE with bounds:', bounds); map.fitBounds(bounds, { padding: [20, 20] }); + setHasRun(true); // Ensure this only runs once ever } - }, [bounds, map, shouldFit]); + }, [bounds, map, shouldFit, hasRun]); return null; }; @@ -183,15 +185,39 @@ const MapView = () => { console.log('MapView: fetchDevices - Device data received, length:', deviceData.length); setDevices(deviceData); - // Just log device bounds for reference, but don't use them - if (deviceData.length > 0) { + // Set initial bounds and center ONLY on first load + if (deviceData.length > 0 && isInitialLoad) { const lats = deviceData.map(device => device.geo_lat); const lons = deviceData.map(device => device.geo_lon); + const minLat = Math.min(...lats); const maxLat = Math.max(...lats); const minLon = Math.min(...lons); const maxLon = Math.max(...lons); - console.log('MapView: Device bounds (info only):', { minLat, maxLat, minLon, maxLon }); + + // Add padding around the bounds (15% on each side for better visibility) + const latPadding = (maxLat - minLat) * 0.15; + const lonPadding = (maxLon - minLon) * 0.15; + + const bounds = [ + [minLat - latPadding, minLon - lonPadding], // Southwest + [maxLat + latPadding, maxLon + lonPadding] // Northeast + ]; + + console.log('MapView: Setting initial bounds and center for devices'); + setMapBounds(bounds); + setShouldFitBounds(true); + + // Calculate center + const centerLat = (minLat + maxLat) / 2; + const centerLon = (minLon + maxLon) / 2; + setMapCenter([centerLat, centerLon]); + + // Disable automatic fitting after initial setup (with longer delay) + setTimeout(() => { + console.log('MapView: Disabling automatic bounds fitting - manual navigation now preserved'); + setShouldFitBounds(false); + }, 2000); } // Always mark initial load as complete after first fetch @@ -276,10 +302,11 @@ const MapView = () => {
+ {mapBounds && }