Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refresh leaflet map: map container is already initialized

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.

like image 521
leandro713 Avatar asked Oct 04 '13 16:10

leandro713


People also ask

How do you refresh a leaflet map?

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();

How do you destroy a leaflet map?

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.

How do you get marker off a leaflet map?

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.


2 Answers

Try map.remove(); before you try to reload the map. This removes the previous map element using Leaflet's library (instead of jquery's).

like image 175
Josh Avatar answered Sep 21 '22 18:09

Josh


the best way

map.off(); map.remove(); 

You should add map.off(), it also works faster, and does not cause problems with the events

like image 25
yit770 Avatar answered Sep 19 '22 18:09

yit770