From 3345da0a8f4f0d4ebfafea0e5ee2a902995c2ea2 Mon Sep 17 00:00:00 2001 From: Kevin Fabre Date: Thu, 21 Sep 2023 15:49:58 +0200 Subject: [PATCH] fix(POI Maps): add map resize observer --- .../src/components/MapPoi/Map.ts | 19 ++++++++++++++++++- .../src/components/MapPoi/MapRender.svelte | 2 +- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/visualizations/src/components/MapPoi/Map.ts b/packages/visualizations/src/components/MapPoi/Map.ts index 9719f69c..5bf5b493 100644 --- a/packages/visualizations/src/components/MapPoi/Map.ts +++ b/packages/visualizations/src/components/MapPoi/Map.ts @@ -1,4 +1,5 @@ import type { BBox } from 'geojson'; +import { debounce } from 'lodash'; import maplibregl, { LngLatBoundsLike, LngLatLike, @@ -13,6 +14,8 @@ const DEFAULT_CENTER: LngLatLike = [3.5, 46]; export default class MapPOI { private map: maplibregl.Map | null = null; + private mapResizeObserver: ResizeObserver | null = null; + private isReady = false; private baseStyle: StyleSpecification | null = null; @@ -31,12 +34,25 @@ export default class MapPOI { this.queuedFunctions = []; } + private initializeMapResizer(map: maplibregl.Map, container: HTMLElement) { + // Set a resizeObserver to resize map on container size changes + this.mapResizeObserver = new ResizeObserver( + debounce(() => { + map.resize(); + }, 100) + ); + this.mapResizeObserver.observe(container); + } + initialize( style: MapOptions['style'], container: HTMLElement, options: Omit ) { this.map = new maplibregl.Map({ style, container, center: DEFAULT_CENTER, ...options }); + + this.queue((map) => this.initializeMapResizer(map, container)); + this.map.on('load', () => { this.isReady = true; // Store base style after the first loads @@ -47,8 +63,9 @@ export default class MapPOI { }); } - remove() { + destroy() { this.queue((map) => map.remove()); + this.mapResizeObserver?.disconnect(); } // TODO: add tests to check that layers are at the end of the array diff --git a/packages/visualizations/src/components/MapPoi/MapRender.svelte b/packages/visualizations/src/components/MapPoi/MapRender.svelte index 12996dd2..a99fb25c 100644 --- a/packages/visualizations/src/components/MapPoi/MapRender.svelte +++ b/packages/visualizations/src/components/MapPoi/MapRender.svelte @@ -27,7 +27,7 @@ // Lifecycle onMount(() => map.initialize(style, container, { bounds: bbox as LngLatBoundsLike })); - onDestroy(() => map.remove()); + onDestroy(() => map.destroy());