-
Notifications
You must be signed in to change notification settings - Fork 3
/
MapRender.svelte
315 lines (278 loc) · 10.5 KB
/
MapRender.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<svelte:options immutable={true} />
<script lang="ts">
import maplibregl, {
Map,
SourceSpecification,
StyleSpecification,
NavigationControl,
LngLatBoundsLike,
MapSourceDataEvent,
MapLayerMouseEvent,
LngLatLike,
} from 'maplibre-gl';
import { onMount } from 'svelte';
import { debounce } from 'lodash';
// eslint-disable-next-line import/no-unresolved
import type { BBox } from 'geojson';
import { computeMaxZoomFromGeoJsonFeatures, getFixedTooltips } from './utils';
import ColorsLegend from '../utils/ColorsLegend.svelte';
import type { ColorsScale, DataBounds, LegendVariant } from '../types';
import type {
ChoroplethFixedTooltipDescription,
MapLayer,
MapRenderTooltipFunction,
MapLegend,
} from './types';
// maplibre style (basemap)
export let style: StyleSpecification;
// maplibre source config
export let source: SourceSpecification;
// maplibre layer config
export let layer: MapLayer;
// bounding box to start from, and restrict to it
export let bbox: BBox;
// option to disable map interactions
export let interactive: boolean;
// options to display legend
export let legend: MapLegend | undefined;
export let colorsScale: ColorsScale;
export let dataBounds: DataBounds;
// Used to render tooltips on hover
export let renderTooltip: MapRenderTooltipFunction;
// Used to select shapes to activate a tooltip on render
export let activeShapes: string[] | undefined;
// aspect ratio based on width, by default equal to 1
export let aspectRatio = 1;
let clientWidth: number;
let legendVariant: LegendVariant;
$: legendVariant = clientWidth <= 375 ? 'fluid' : 'fixed';
// Used to store fixed tooltips displayed on render
// FIXME: This may not be useful anymore, and is very tied to Choropleth right now
let fixedPopupsList: ChoroplethFixedTooltipDescription[] = [];
$: cssVarStyles = `--aspect-ratio:${aspectRatio};`;
let container: HTMLElement;
let map: Map;
// Used to add navigation control to map
let nav: NavigationControl;
let mapReady = false;
// Used to add a listener to resize map on container changes, canceled on destroy
let resizer: ResizeObserver;
const hoverPopup = new maplibregl.Popup({
closeOnClick: false,
closeButton: false,
className: 'tooltip-on-hover',
}).trackPointer();
// Used in front of console and error messages to debug multiple maps on a same page
const mapId = Math.floor(Math.random() * 1000);
const sourceId = `shape-source-${mapId}`;
const layerId = `shape-layer-${mapId}`;
function fitMapToBbox(newBbox: BBox) {
// Cancel saved max bounds to properly fitBounds
map.setMaxBounds(null);
map.fitBounds(newBbox as LngLatBoundsLike, {
animate: false,
padding: 10,
});
// Rest min zoom and movement
map.setMaxBounds(map.getBounds());
}
function initializeMap() {
const defaultCenter: LngLatLike = [3.5, 46];
const start = {
center: defaultCenter,
zoom: 5,
};
map = new maplibregl.Map({
container,
style,
...start,
});
nav = new maplibregl.NavigationControl({});
map.on('load', () => {
mapReady = true;
});
return () => map.remove();
}
function initializeResizer() {
// Set a resizeObserver to resize map on container size changes
// TODO: Do we really want to reset to the initial bbox each time?
resizer = new ResizeObserver(
debounce(() => {
map.resize();
if (mapReady && bbox) {
fitMapToBbox(bbox);
}
}, 100)
);
resizer.observe(container);
// Disconnect the resize onDestroy
return () => resizer?.disconnect();
}
function sourceLoadingCallback(e: MapSourceDataEvent) {
// sourceDataType can be "visibility" or "metadata", in which case it's not about the data itself
if (e.isSourceLoaded && e.sourceId === sourceId && !e.sourceDataType) {
// The type forces you to pass a filter parameter in the option, but it's not required by the real code
// https://github.com/maplibre/maplibre-gl-js/issues/1393
// @ts-ignore
const renderedFeatures = map.querySourceFeatures(sourceId, { sourceLayer: layerId });
if (renderedFeatures.length) {
// Restrict zoom max
// TODO: We may not catch the smaller shapes if Maplibre discarded them for rendering reasons, so it's a bit risky. Is it worth it?
// A low-cost approach could be to restrict the zoom scale to an arbitrary value (e.g. only 4 from the max zoom)... or not restrict at all.
const maxZoom = computeMaxZoomFromGeoJsonFeatures(container, renderedFeatures);
map.setMaxZoom(maxZoom);
if (activeShapes && activeShapes.length > 0 && renderTooltip) {
fixedPopupsList = getFixedTooltips(
activeShapes,
renderedFeatures,
renderTooltip
);
}
}
map.off('sourcedata', sourceLoadingCallback);
}
}
function addTooltip(e: MapLayerMouseEvent) {
// @ts-ignore // Somehow `features` isn't part of the type, but exists in the object at runtime
const description = renderTooltip(e.features[0]);
if (hoverPopup.isOpen()) {
hoverPopup.setLngLat(e.lngLat).setHTML(description);
} else {
hoverPopup.setLngLat(e.lngLat).setHTML(description).addTo(map);
}
}
function removeTooltip() {
hoverPopup.remove();
}
function handleInteractivity(
isInteractive: boolean,
tooltipRenderer?: MapRenderTooltipFunction
) {
if (isInteractive) {
// Enable all user interaction handlers
// Another way to disable all user handlers is to pass the option interactive = false on map creation
// But it doesn't allow to change it afterwards
// Id est it forces you to recreate another map if you want to change that option
map.boxZoom.enable();
map.doubleClickZoom.enable();
map.dragPan.enable();
map.dragRotate.enable();
map.keyboard.enable();
map.scrollZoom.enable();
map.touchZoomRotate.enable();
// Add navigation control to map
if (!map.hasControl(nav)) {
map.addControl(nav, 'top-left');
}
// Handle tooltip display
map.off('mousemove', layerId, addTooltip);
map.off('mouseleave', layerId, removeTooltip);
if (tooltipRenderer) {
map.on('mousemove', layerId, addTooltip);
map.on('mouseleave', layerId, removeTooltip);
}
} else {
// Disable all user interaction handlers
map.boxZoom.disable();
map.doubleClickZoom.disable();
map.dragPan.disable();
map.dragRotate.disable();
map.keyboard.disable();
map.scrollZoom.disable();
map.touchZoomRotate.disable();
// Remove tooltip
map.off('mousemove', layerId, addTooltip);
map.off('mouseleave', layerId, removeTooltip);
// Remove navigation control from map
if (map.hasControl(nav)) {
map.removeControl(nav);
}
// Reset map zoom
if (mapReady && bbox) {
fitMapToBbox(bbox);
}
}
}
function updateSourceAndLayer(newSource: SourceSpecification, newLayer: MapLayer) {
if (newSource && newLayer) {
if (map.getLayer(layerId)) {
map.removeLayer(layerId);
}
if (map.getSource(sourceId)) {
map.removeSource(sourceId);
}
map.addSource(sourceId, newSource);
map.addLayer({
...newLayer,
id: layerId,
source: sourceId,
});
map.on('sourcedata', sourceLoadingCallback);
}
}
function updateStyle(newStyle: StyleSpecification) {
if (mapReady) {
map.setStyle(newStyle);
// Changing the style resets the map
map.once('styledata', () => updateSourceAndLayer(source, layer));
}
}
// Lifecycle
onMount(initializeMap);
onMount(initializeResizer);
$: if (mapReady) {
updateSourceAndLayer(source, layer);
}
$: if (mapReady) {
handleInteractivity(interactive, renderTooltip);
}
$: updateStyle(style);
$: if (mapReady && bbox) {
fitMapToBbox(bbox);
}
$: if (fixedPopupsList?.length > 0 && (activeShapes?.length === 0 || !activeShapes)) {
fixedPopupsList.forEach((fixedPopup) => fixedPopup.popup.remove());
}
$: fixedPopupsList.forEach((fixedPopup) => {
const { center, description, popup } = fixedPopup;
popup
.setLngLat(center as LngLatLike)
.setHTML(description)
.addTo(map);
});
</script>
<figure class="map-card" style={cssVarStyles} bind:clientWidth>
<div id="map" bind:this={container} />
{#if legend && dataBounds && clientWidth && mapReady}
<ColorsLegend {dataBounds} {colorsScale} variant={legendVariant} title={legend.title} />
{/if}
</figure>
<style>
#map {
height: 400px;
}
@supports (aspect-ratio: auto) {
#map {
height: auto;
aspect-ratio: var(--aspect-ratio);
}
}
.map-card {
display: flex;
flex-direction: column;
margin: 0;
position: relative;
}
/* To add classes programmatically in svelte we will use a global selector. We place it inside a local selector to obtain some encapsulation and avoid side effects */
.map-card :global(.tooltip-on-hover > .maplibregl-popup-content) {
border-radius: 6px;
box-shadow: 0px 6px 13px rgba(0, 0, 0, 0.26);
padding: 13px;
}
.map-card :global(.tooltip-on-hover .maplibregl-popup-tip) {
border-top-color: transparent;
border-bottom-color: transparent;
border-left-color: transparent;
border-right-color: transparent;
}
</style>