Skip to content

Commit 2ec2f1e

Browse files
committed
Center map on marker when clicked or changed
1 parent b018c54 commit 2ec2f1e

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

webapp/components/PollutionMapMarker.tsx

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,12 +161,23 @@ export default function PollutionMapMarker({
161161
> | null>(null);
162162
const [showPopup, setShowPopup] = useState<boolean>(true);
163163

164-
// Show popup when marker changes
164+
// Show popup when marker changes and center map on marker
165165
useEffect(() => {
166-
if (marker) {
166+
if (marker && map) {
167167
setShowPopup(true);
168+
// Center the map on the marker with vertical offset
169+
const mapContainer = map.getContainer();
170+
const mapHeight = mapContainer.offsetHeight;
171+
const offsetY = mapHeight * 0.1; // 60% from top -> 10% offset from center
172+
173+
map.flyTo({
174+
center: [marker.longitude, marker.latitude],
175+
zoom: Math.max(map.getZoom(), 8), // Ensure minimum zoom level
176+
duration: 1000,
177+
offset: [0, offsetY],
178+
});
168179
}
169-
}, [marker]);
180+
}, [marker, map]);
170181

171182
useEffect(() => {
172183
if (!map || !marker) return;
@@ -593,7 +604,22 @@ export default function PollutionMapMarker({
593604
longitude={marker.longitude}
594605
latitude={marker.latitude}
595606
anchor="bottom"
596-
onClick={() => setShowPopup(true)}
607+
onClick={() => {
608+
setShowPopup(true);
609+
// Center the map on the marker with vertical offset when clicked
610+
if (map) {
611+
const mapContainer = map.getContainer();
612+
const mapHeight = mapContainer.offsetHeight;
613+
const offsetY = mapHeight * 0.1; // 40% from top means 10% offset from center
614+
615+
map.flyTo({
616+
center: [marker.longitude, marker.latitude],
617+
zoom: Math.max(map.getZoom(), 8), // Ensure minimum zoom level
618+
duration: 1000,
619+
offset: [0, -offsetY], // Negative Y moves the center point up
620+
});
621+
}
622+
}}
597623
>
598624
<MapPin
599625
size={32}

0 commit comments

Comments
 (0)