Files
Overheard/src/lib/components/MapView.Svelte
2026-06-08 16:23:24 +09:00

93 lines
3.0 KiB
Svelte

<script>
import { onMount } from 'svelte';
import { env } from '$env/dynamic/public';
import { messagesStore } from '$lib/stores/messagesStore.js'; // pass the messages store here
import { mapStore } from '$lib/stores/mapStore.js'; // use this to track interactions with da map
// export let latitude;
// export let longitude;
// ^ this didn't work for some reason, so instead we get the props like this: (based on internet research this is the fix)
let { lat, lng } = $props();
let mapDiv;
let userMarker = null;
let markers = []; // keep track of pins on map
/** 내 위치 마커 (메시지 핀과 구분되는 파란 점) */
function addUserLocationMarker(map, centerLat, centerLng) {
userMarker = new google.maps.Marker({
position: { lat: centerLat, lng: centerLng },
map,
title: 'Your location',
zIndex: 1000,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10,
fillColor: '#4285F4',
fillOpacity: 1,
strokeColor: '#ffffff',
strokeWeight: 3
}
});
}
onMount (async () => {
const centerLat = Number(lat);
const centerLng = Number(lng);
const { setOptions, importLibrary } = await import('@googlemaps/js-api-loader');
setOptions({
key: env.PUBLIC_MAPS_KEY,
version: 'weekly',
});
const { Map } = await importLibrary('maps');
mapDiv = new Map(mapDiv, {
center: { lat: centerLat, lng: centerLng },
zoom: 15,
disableDefaultUI: true,
gestureHandling: 'greedy'
});
addUserLocationMarker(mapDiv, centerLat, centerLng);
});
// function to rended pins
function renderPins(messages) {
// clear current pins
markers.forEach(marker => marker.setMap(null)); // make them not show up
markers = []; // reset the array
messages.forEach(message => {
const marker = new google.maps.Marker({
position: { lat: message.lat, lng: message.lng}, // lat and lng is what is called in the firestore documents
map: mapDiv,
title: message.text // firestore field for messages
});
marker.addListener('click', () => {
mapStore.set({ selectedMessage: message, composing: false}); //it updated the message object
});
markers.push(marker); // add the new pin to the array
});
}
// this is a reactive statement so anytime the store changes it updates
$effect(() => {
if (mapDiv && $messagesStore.length > 0 ){ // if they both exist
renderPins($messagesStore); // we put pins on the map
}
})
</script>
<div class="map" bind:this={mapDiv}></div>
<style>
.map {
width: 100%;
min-height: 100vh;
}
</style>