aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/LocationsMap.svelte
blob: 4b1b1b82c2442360401e1a5f4359c740b4979f8b (plain) (blame)
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
<script>
	import { onMount, onDestroy } from 'svelte';
	import { browser } from '$app/environment';
	import html2canvas from 'html2canvas';
	import { Icon } from '$comp';

	import 'maplibre-gl/dist/maplibre-gl.css';

	export let locations;
	let map;
	let mapContainer, mapWrapper;
	let markers = [];

	let currentIndex = -1;
	let timeout;

	let full = () => {
		if (!document.fullscreenElement) {
			if (mapWrapper.requestFullscreen) {
				mapWrapper.requestFullscreen();
			} else if (mapWrapper.mozRequestFullScreen) {
				/* Firefox */
				mapWrapper.mozRequestFullScreen();
			} else if (mapWrapper.webkitRequestFullscreen) {
				/* Chrome, Safari & Opera */
				mapWrapper.webkitRequestFullscreen();
			} else if (mapWrapper.msRequestFullscreen) {
				/* IE/Edge */
				mapWrapper.msRequestFullscreen();
			}

      map.resize();
		} else {
			if (document.exitFullscreen) {
				document.exitFullscreen();
			} else if (document.mozCancelFullScreen) {
				/* Firefox */
				document.mozCancelFullScreen();
			} else if (document.webkitExitFullscreen) {
				/* Chrome, Safari and Opera */
				document.webkitExitFullscreen();
			} else if (document.msExitFullscreen) {
				/* IE/Edge */
				document.msExitFullscreen();
			}
		}
	};

	function select(m) {
		stopFlying();
		currentIndex = inview.indexOf(m);
		flyToMarker(m);
	}

	async function flyToMarker(marker) {
		marker.getElement().click();

		map.flyTo({
			zoom: 14,
			center: marker.getLngLat(),
			essential: true,
			easing: function (t) {
				return 1 - Math.pow(1 - t, 3);
			},
			duration: 5000
		});

		await new Promise((r) => setTimeout(r, 5000));

		if (!timeout) return;

		map.flyTo({
			zoom: 10.5,
			center: marker.getLngLat(),
			essential: true,
			easing: function (t) {
				return 1 - Math.pow(1 - t, 3);
			},
			duration: 2000
		});
	}

	let toggle = () => {
		if (timeout) stopFlying();
		else startFlying();
	};

	let currentPopup;
	function startFlying() {
		currentIndex++;

		for (let p in popups) popups[p].remove();
		if (currentIndex >= inview.length) currentIndex = 0;
		flyToMarker(inview[currentIndex]);

		timeout = setTimeout(startFlying, 7000);
	}

	function stopFlying() {
		if (!timeout) return;
		timeout = clearTimeout(timeout);

		if (currentPopup) {
			currentPopup.remove();
		}

		map.jumpTo({ center: map.getCenter(), zoom: map.getZoom() });
		map.off('moveend'); // Remove moveend listener if set
	}

	let checkAddress = (location) => {
		if (location['addr:housenumber'] && location['addr:street'] && location['addr:city']) {
			return `${
				location['addr:housenumber'] + ' ' + location['addr:street'] + ', ' + location['addr:city']
			}`;
		} else if (location['addr:street'] && location['addr:city']) {
			return `${location['addr:street'] + ', ' + location['addr:city']}`;
		} else if (location['addr:city']) {
			return `${location['addr:city']}`;
		} else {
			return '';
		}
	};

	let inview = [];

	function updateLabelVisibility() {
		inview = [];
		if (!map) return;
		let zoom = map.getZoom();
		let bounds = map.getBounds();

		for (let marker of markers) {
			let isInView = bounds.contains(marker.getLngLat());
			let { tags } = marker;

			if (isInView) {
				inview.push(marker);
			}
		}

		inview = inview.sort((a, b) => a.tags.name.localeCompare(b.tags.name));
	}

	let html = (tags) => `${
		tags && tags.name ? `<span class='block font-bold'>${tags.name}</span>` : ''
	}

  <span class='block'>${tags && checkAddress(tags)}</span>

  ${tags && tags.phone ? `<a href='tel:${tags.phone}' class='block'>${tags.phone}</a>` : ''}

  ${
		tags && tags.website
			? `<a href=${tags.website} target="_blank" rel="noreferrer" class='block text-blue-400 break-all'>${tags.website}</a>`
			: ''
	}`;

	let popups = {};
	let counter = 0;

	onMount(() => {
		if (browser) {
			import('maplibre-gl').then(({ default: maplibre }) => {
				map = new maplibre.Map({
					container: mapContainer,
					style: 'https://tiles.stadiamaps.com/styles/stamen_toner.json',
					center: [-123.05, 49.26],
					zoom: 10.5
				});

				map.on('load', () => {
					locations.forEach((location) => {
						if (location['deleted_at']) return;

						let { lat, lon, tags } = location['osm_json'];
						if (!(lat && lon)) return;

						let element = document.createElement('div');
						element.className = 'marker';

						let marker = new maplibre.Marker({ color: '#F7931A' })
							.setLngLat([lon, lat])
							.setPopup(new maplibre.Popup().setHTML(html(tags)))
							.addTo(map);

						marker.id = counter++;

						marker.getElement().addEventListener('click', () => {
							let h = html(marker.tags);
							let p = marker.getPopup();
							popups[marker.id] = p;
							p.setHTML(h);
							p.on('close', () => {
								delete popups[marker.id];
							});
						});

						marker.tags = tags;

						markers.push(marker);
					});

					updateLabelVisibility();

					let observer = new IntersectionObserver(
						(entries, observer) => {
							entries.forEach((entry) => {
								if (entry.isIntersecting) startFlying();
								else stopFlying();
							});
						},
						{ threshold: 0.5 }
					);

					observer.observe(mapContainer);
				});

				map.on('mousedown', stopFlying);
				map.on('touchstart', stopFlying);
				map.on('wheel', stopFlying);
				map.on('dragstart', stopFlying);

				document.addEventListener('fullscreenchange', onFullScreenChange, false);
				document.addEventListener('webkitfullscreenchange', onFullScreenChange, false);
				document.addEventListener('mozfullscreenchange', onFullScreenChange, false);
				document.addEventListener('MSFullscreenChange', onFullScreenChange, false);

				function onFullScreenChange() {
          console.log("resizing")
					if (map) {
						map.resize(); // This will adjust the map size to fit the new container size
					}
				}
			});
		}
	});

	onDestroy(() => {
		if (map) {
			map.remove();
		}
	});
</script>

<div class="container mx-auto max-w-4xl">
	<div class="flex w-full h-[400px]" id="map" bind:this={mapWrapper}>
		<div id="map-container" class="mx-auto h-full w-full z-0" bind:this={mapContainer} />
		<div class="relative">
			<div class="flex absolute flex top-2 right-2 gap-2">
				<button class="rounded-full border-2 border-black bg-white w-10 h-10" on:click={toggle}>
					{#if timeout}
						<Icon icon="pause" style="w-4 m-auto" />
					{:else}
						<Icon icon="play" style="w-4 m-auto" />
					{/if}
				</button>
				<button class="rounded-full border-2 border-black bg-white w-10 h-10" on:click={full}>
					<Icon icon="full" style="w-4 m-auto" />
				</button>
			</div>

			<div class="absolute bottom-2 right-2 w-60 h-24 bg-white overflow-y-scroll p-4 bg-opacity-80">
				{#each inview as m}
					<button
						on:click={() => select(m)}
						class="text-left"
						class:font-bold={m.id === inview[currentIndex]?.id}
						id={`marker-${m.id}`}>{m.tags.name}</button
					>
				{/each}
			</div>
		</div>
	</div>
</div>

<style>
	#map:fullscreen,
	#map-container:fullscreen {
		width: 100% !important;
		height: 100% !important;
	}

	:global(.maplibregl-popup-close-button) {
		font-size: 24px;
		padding: 8px;
	}

	:global(.maplibregl-popup :focus) {
		outline: none;
	}

	:global(.maplibregl-ctrl-attrib) {
		display: none;
	}

	:global(.maplibregl-popup-content) {
		padding: 1em 2em;
		border-radius: 4px;
		font-size: 14px;
		color: black;
		background-color: white;
		overflow: hidden;
		width: 280px;
	}
</style>