Skip to content

Commit

Permalink
fix(POI Maps): add map resize observer
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinFabre-ods committed Sep 21, 2023
1 parent 4e7b43d commit 3345da0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
19 changes: 18 additions & 1 deletion packages/visualizations/src/components/MapPoi/Map.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BBox } from 'geojson';
import { debounce } from 'lodash';
import maplibregl, {
LngLatBoundsLike,
LngLatLike,
Expand All @@ -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;
Expand All @@ -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<MapOptions, 'style' | 'container'>
) {
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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
// Lifecycle
onMount(() => map.initialize(style, container, { bounds: bbox as LngLatBoundsLike }));
onDestroy(() => map.remove());
onDestroy(() => map.destroy());
</script>

<figure class="map-card maps-container" style={cssVarStyles}>
Expand Down

0 comments on commit 3345da0

Please sign in to comment.