i am not a java script person. please point out what iI am doing here ; map gets loaded fine if i do a manual refesh with Ctrl+R . No error on console.
import "@/styles/global.css";
import { ClientRouter } from "astro:transitions";
---
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<ClientRouter />
<link rel="stylesheet" href="/leaflet/leaflet.css" />
<script is:inline src="/leaflet/leaflet.js" defer></script>
</head>
<body>
<div id="map" class="h-128 w-full border border-gray-300"></div>
</body>
<script is:inline>
if (!window.mapInstance) {
window.mapInstance = null;
}
function leafletmap() {
const mapContainer = document.getElementById("map");
if (mapContainer) {
if (window.mapInstance) {
window.mapInstance.remove();
}
const tiles = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a>',
});
// Create the map
window.mapInstance = L.map("map", {
center: [39.42752947035746, 35.60132306248704],
zoom: 2,
layers: [tiles],
});
}
}
function cleanupMap() {
if (window.mapInstance) {
window.mapInstance.remove();
window.mapInstance = null;
}
}
window.addEventListener('load', () => {
if (document.getElementById("map")) {
leafletmap();
}
});
document.addEventListener("astro:after-swap", () => {
if (document.getElementById("map")) {
leafletmap();
}
});
document.addEventListener("astro:before-swap", cleanupMap);
</script>
</html>