rendering pins on map based on firestore document

This commit is contained in:
2026-06-06 13:58:26 +09:00
parent 8dcdd7a0e4
commit b8567ef513
4 changed files with 49 additions and 2 deletions

View File

@@ -1,13 +1,16 @@
<script>
import { onMount } from 'svelte';
import { env } from '$env/dynamic/public';
import { messagesStore } from '$lib/stores/messagesStore.js'; // pass the messages store here
// 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; // reference ot the map <div> below
let mapDiv;
let markers = []; // keep track of pins on map
onMount (async () => {
const centerLat = Number(lat);
@@ -21,13 +24,36 @@
const { Map } = await importLibrary('maps');
new Map(mapDiv, {
mapDiv = new Map(mapDiv, {
center: { lat: centerLat, lng: centerLng },
zoom: 15,
disableDefaultUI: true,
gestureHandling: 'greedy'
});
});
// 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
});
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>

View File

@@ -0,0 +1,8 @@
import { writable } from 'svelte/store';
// keeping track of user interactions with messages
export const mapStore = writable({
selectedMessage: null, // message user clicked on
composing: false // user making a message
});

View File

@@ -0,0 +1,3 @@
import { writable } from 'svelte/store';
export const messagesStore = writable([]); // the store will fill up when the page lloads and queries firestore

View File

@@ -3,6 +3,8 @@
import MapView from '$lib/components/MapView.svelte';
import { getNearbyMessages } from '$lib/firebase/messages.js';
import { messagesStore } from '$lib/stores/messagesStore.js';
let lat = $state();
let lng = $state();
@@ -22,6 +24,14 @@
error = "Location access denied. Please enable location to use Overheard.";
}
);
// populate the messages store
navigator.geolocation.getCurrentPosition(
async (position) => {
const messages = await getNearbyMessages(position.coords.latitude, position.coords.longitude);
messagesStore.set(messages);
console.log('messages loaded:', $messagesStore);
}
);
});