I have installed Leaflet and created a map with several markers. The map works correctly, but the markers are only visible when I zoom in. I want the markers to always be visible regardless of the zoom level. How can I achieve this?
Here’s a snippet of my code:
<template>
<section class="py-16">
<h1 class="text-5xl font-medium capitalize text-tfc-550 my-4 text-center">
Sedi
</h1>
<section>
<div v-if="isClient" class="w-full h-140" id="map">
</div>
<div v-else class="text-center text-gray-500">
Caricamento della mappa in corso...
</div>
</section>
</section>
</template>
<script setup lang="ts">
import "leaflet/dist/leaflet.css"
import { ref, onMounted } from "vue"
const isClient = ref(false)
onMounted(async () => {
isClient.value = true
if (typeof window !== "undefined") {
const L = (await import("leaflet")).default
//@ts-ignore
await import("leaflet.markercluster")
const map = L.map("map")
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "© OpenStreetMap contributors",
}).addTo(map)
const markers = L.markerClusterGroup()
// Marker data
const sedi = [
{ lat: 41.896852, lng: 12.481293, name: "Roma" },
{ lat: 45.532203, lng: 10.208898, name: "Brescia" },
{ lat: 45.483062, lng: 9.206098, name: "Milano" },
{ lat: 40.678369, lng: 14.765663, name: "Salerno" },
{ lat: 40.834449, lng: 14.229847, name: "Napoli" }
]
sedi.forEach((sede) => {
const marker = L.marker([sede.lat, sede.lng]).bindPopup(`<b>${sede.name}</b>`)
markers.addLayer(marker)
})
map.addLayer(markers)
setTimeout(() => {
const bounds = markers.getBounds()
if (bounds.isValid()) {
map.fitBounds(bounds)
} else {
console.error("Bounds non validi. Controlla i dati dei marker.")
}
map.invalidateSize()
}, 100)
}
})
</script>
<style scoped>
</style>
Here are my installed dependencies:
"dependencies": {
"@nuxtjs/leaflet": "^1.2.6",
"@pinia/nuxt": "^0.7.0",
"@vueuse/core": "^10.7.2",
"apexcharts": "^3.45.2",
"glightbox": "^3.3.0",
"gumshoejs": "^5.1.2",
"leaflet.markercluster": "^1.5.3",
"lucide-vue-next": "^0.469.0",
"nuxt": "^3.14.1592",
"pinia": "^2.2.6",
"preline": "^2.0.3",
"swiper": "^11.0.6",
"vue": "^3.5.13",
"vue-router": "^4.5.0",
"vue3-apexcharts": "^1.5.2"
},
"devDependencies": {
"@nuxtjs/tailwindcss": "^6.12.2",
"@tailwindcss/forms": "^0.5.9",
"@tailwindcss/nesting": "^0.0.0-insiders.565cd3e",
"@tailwindcss/typography": "^0.5.15",
"autoprefixer": "^10.4.20",
"nuxt-anchorscroll": "^1.0.3",
"postcss": "^8.4.49",
"postcss-import": "^16.1.0",
"prettier": "^3.3.3",
"tw-colors": "^3.3.2"
}
Thank you in advance for your help!