Merge pull request #135 from trails-cool/copilot/change-map-zoom-for-route

Fit map to route bounds on open
This commit is contained in:
Ullrich Schäfer 2026-03-29 19:38:05 +02:00 committed by GitHub
commit f6b89a2b7e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 51 additions and 0 deletions

View file

@ -54,6 +54,32 @@ function MapExposer() {
return null;
}
function RouteFitter({ coordinates }: { coordinates: [number, number, number][] | null }) {
const map = useMap();
const hasFitted = useRef(false);
useEffect(() => {
if (hasFitted.current || !coordinates || coordinates.length < 2) return;
// Coordinates are in [lon, lat, elevation] GeoJSON format
const bounds = L.latLngBounds(
coordinates.map((c) => [c[1]!, c[0]!] as [number, number]),
);
if (!bounds.isValid()) return;
// Delay fitBounds so the layout has settled (elevation chart may resize the map)
const raf = requestAnimationFrame(() => {
map.invalidateSize();
map.fitBounds(bounds, { padding: [50, 50], maxZoom: 16 });
hasFitted.current = true;
});
return () => cancelAnimationFrame(raf);
}, [coordinates, map]);
return null;
}
function MapClickHandler({ onAdd, suppressRef }: { onAdd: (lat: number, lng: number) => void; suppressRef: React.RefObject<boolean> }) {
useMapEvents({
click(e) {
@ -314,6 +340,7 @@ export function PlannerMap({ yjs, onRouteRequest, highlightPosition }: PlannerMa
</LayersControl>
<MapExposer />
<RouteFitter coordinates={routeCoordinates} />
<MapClickHandler onAdd={noGoDrawing ? () => {} : addWaypoint} suppressRef={suppressMapClickRef} />
<CursorTracker awareness={yjs.awareness} />
<NoGoAreaLayer noGoAreas={yjs.noGoAreas} doc={yjs.doc} enabled={noGoDrawing} onToggle={toggleNoGoDraw} />

View file

@ -151,6 +151,30 @@ test.describe("Planner", () => {
await expect(page.getByTitle("Draw no-go area")).toBeVisible();
});
test("map zooms to fit the route when opened with initial waypoints", async ({ page, request }) => {
const sessionResp = await request.post("/api/sessions", { data: {} });
const { url } = await sessionResp.json();
const waypoints = [
{ lat: 52.520, lon: 13.405 },
{ lat: 52.515, lon: 13.351 },
];
await page.goto(`${url}?waypoints=${encodeURIComponent(JSON.stringify(waypoints))}`);
await expect(page.locator(".leaflet-container")).toBeVisible({ timeout: 10000 });
await expect(page.getByText("Connected")).toBeVisible({ timeout: 15000 });
// Wait for route to compute and fit
await expect(page.getByText(/\d+\.\d+ km/)).toBeVisible({ timeout: 20000 });
// The map should have zoomed in to the route bounds (zoom > default 6)
const zoom = await page.evaluate(() => {
const map = (window as any).__leafletMap;
return map ? map.getZoom() : null;
});
expect(zoom).not.toBeNull();
expect(zoom).toBeGreaterThan(6);
});
test("can create session with initial waypoints", async ({ request }) => {
const response = await request.post("/api/sessions", {
data: {