refresh leaflet map: map container is already initialized

leandro713 picture leandro713 · Oct 4, 2013 · Viewed 109.4k times · Source

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.

Answer

Josh picture Josh · Oct 5, 2013

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