From 90fd35eb49cdcd6e0cb132560e057313a9428ee9 Mon Sep 17 00:00:00 2001 From: Michel Jung Date: Tue, 18 Apr 2023 23:47:41 +0200 Subject: [PATCH] Fix camera repositioning for single node (#104) * Fix camera repositioning for single node Before, camera repositioning only worked when there were at least two nodes, even though the code was meant to handle single nodes as well. This is related to #86 but doesn't fix it. * Center camera on nodes when opening map Fixes #86 --- src/pages/Map.tsx | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/pages/Map.tsx b/src/pages/Map.tsx index f1f47ff6..84bd0c80 100644 --- a/src/pages/Map.tsx +++ b/src/pages/Map.tsx @@ -28,10 +28,21 @@ export const MapPage = (): JSX.Element => { const allNodes = Array.from(nodes.values()); const getBBox = () => { + if (!map) return; const nodesWithPosition = allNodes.filter( (node) => node.position?.latitudeI ); if (!nodesWithPosition.length) return; + if (nodesWithPosition.length === 1) { + map.easeTo({ + zoom: 12, + center: [ + (nodesWithPosition[0].position?.longitudeI ?? 0) / 1e7, + (nodesWithPosition[0].position?.latitudeI ?? 0) / 1e7 + ] + }); + return; + } const line = lineString( nodesWithPosition.map((n) => [ (n.position?.latitudeI ?? 0) / 1e7, @@ -39,22 +50,14 @@ export const MapPage = (): JSX.Element => { ]) ); const bounds = bbox(line); - const center = map?.cameraForBounds( + const center = map.cameraForBounds( [ [bounds[1], bounds[0]], [bounds[3], bounds[2]] ], { padding: { top: 10, bottom: 10, left: 10, right: 10 } } ); - if (center) map?.easeTo(center); - else if (nodesWithPosition.length === 1) - map?.easeTo({ - zoom: 12, - center: [ - (nodesWithPosition[0].position?.longitudeI ?? 0) / 1e7, - (nodesWithPosition[0].position?.latitudeI ?? 0) / 1e7 - ] - }); + if (center) map.easeTo(center); }; useEffect(() => { @@ -63,6 +66,12 @@ export const MapPage = (): JSX.Element => { }); }, [map, zoom]); + useEffect(() => { + if (map) { + getBBox(); + } + }, [map]); + return ( <>