For a personal project, I had to use Leaflet with Svelte, and I faced some problems during development.
In this article, I will list each point that required finding a solution.
Integrating Leaflet into a SvelteKit project
I highly recommend that you read the article Using Leaflet with SvelteKit written by Stanislav Khromov.
He explains an effective way to add Leaflet to a project made with SvelteKit. It was my starting point in my project.
Install Leaflet.markercluster plugin
You can retrieve this plugin from its official repo on Github : Leaflet.markercluster.
I used npm to add it to my project.
npm install leaflet.markercluster
Now, it needs to be integrated into the code of the file LeafletMap.svelte
.
onMount(async () => { if (browser) { const leaflet = await import('leaflet'); const { MarkerClusterGroup }: any = await import('leaflet.markercluster');
Afterwards, we can declare the variable lower in the file, and add each marker to the markers
element. Finally, add all the markers to the map.
// L.MarkerClusterGroup extends L.FeatureGroup // by clustering the markers contained within let markers = new MarkerClusterGroup(); // create feature group // for each marker, add it to markers markers.addLayer(marker); // Add all markers to map map.addLayer(markers);
Of course, don’t forget to add the CSS style.
@import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
Bug of icons in production environment
The Leaflet framework can give an error once the project is deployed, the path to the icon causes a 404 (not found) error. To remedy this, one of the solutions is to manually define the icon with an image available in the project’s assets
.
const iconRetinaUrl = './images/leaflet/marker-icon-2x.png'; const iconUrl = './images/leaflet/marker-icon.png'; const shadowUrl = './images/leaflet/marker-shadow.png'; const iconDefault = leaflet.icon({ iconRetinaUrl, iconUrl, shadowUrl, iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], tooltipAnchor: [16, -28], shadowSize: [41, 41] });
Afterwards, you need to use the iconDefault
variable in the marker definition, for example:
leaflet.marker(coords, { icon: iconDefault })
By using the iconDefault
variable in the marker definition, you can ensure that all markers use the same default icon.
Et voilà 🎉
These are the only errors I had to correct during my development, I hope this article will be useful to you.
Top comments (2)
Yes, from Github issues : github.com/Leaflet/Leaflet/issues/...
Did you find the root cause for this icon issue? Seems so weird