I have a page where given a select to the user he can switch the leaflet map I show.
After a initial leaflet map load, my problem is when i want to refresh the map.
I always get "Map container is already initialized":
The problem line is:
var map = L.map('mapa').setView([lat, lon], 15);
Initially it loads well, but when I select another parameter in the form and want to display the map another time it crashes.
btw, I've tried to destroy and recreate $('#mapa')
with jQuery before the second setView()
but it shows the same error.
To refresh leaflet map when map container is already initialized with JavaScript, we call the off and remove methods before reloading the map. map. off(); map. remove();
Example function I use to recreate div and map: var map, mapDiv; recreateMap = function(){ // destroy previous map and div if(map) map. remove(); if(mapDiv) mapDiv. parentNode.
Layergroup allows to control all markers at once. Ok, removing the layer seems to be the solution, but the more straightforward answer to the question, how to remove a marker is the one given by @HarijsKrūtainis : marker. remove() , it worked perfectly to me.
Try map.remove();
before you try to reload the map. This removes the previous map element using Leaflet's library (instead of jquery's).
the best way
map.off(); map.remove();
You should add map.off(), it also works faster, and does not cause problems with the events
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With