Different things to try when troubleshooting "Map container is already initialized"
. Keep in mind all of my usage has been web app context.
(A) Remove the map if it's already initialized
if (map != undefined) map.remove()
(B) Use a unique ID or key
On your map container, use a key that will invoke a fresh rendering:
e.g. in React, you may try:
key={new Date().getTime()}
Or, use a unique id
For example, in Vue I do this:
<div :id="id"></div>
data() {
return {
id: 'mapLeaflet-'+Date.now()
}
}
And anywhere I refer to the DOM element, I use this.id
:
let mapHTMLContainer = document.getElementById(this.id)
(C) Before map init, check existence of map first
Obviously, if you have other trouble, do some hard checks.
In Vue, I do this:
methods: {
initMap() {
let mapHTMLContainer = document.getElementById(this.id)
if (mapHTMLContainer
&& mapHTMLContainer.hasChildNodes() == false
&& !this.map) {
// DO STUFF
// e.g. initialize leaflet, set tile layer, add markers, etc
}
}
}
(D) On map init, pass the actual HTML element, not just a string
When initiating Leaflet map, pass the actual HTML element instead of just the string id.
Both methods are officially supported, but I cannot find any information talking about the differences. https://leafletjs.com/reference.html#map-l-map
BEFORE
This works in general and is convenient...
this.map = L.map("mymap")
AFTER
... but, instead try to actually get the element, and pass it. I observed a difference doing this.
let myMapElement = document.getElementById(this.id)
this.map = L.map(myMapElement)
(E) On component "dismount" destroy things
If you have a dismount state, use it and destroy stuff related to your map component. Make sure things don't hang-around.
In Vue, I do this:
beforeDestroy() {
// Destroy any listeners
this.$nuxt.$off('refreshMap') // Nuxt is the framework I use
// Clear the map instance in your component
if (this.map) {
// I haven't fully tested these; are they valid?
this.map.off() // Leaflet function
this.map.remove() // Leaflet function
this.map = null // null it for good measure
}
// Clear out the HTML container of any children, just in case
let mapHTMLElement = document.getElementById(this.id)
if (mapHTMLElement) {
mapHTMLElement.outerHTML = ""
}
}
nuxt-leaflet
during unit testing withJest
, but can't reproduce it anymore. Based on the test, I could solve it by creating a dummyDiv ``` const dummyDiv: HTMLDivElement = global.document.createElement("div"); const dummyID: string = "dummyID"; dummyDiv.setAttribute("id", dummyID); global.document.body.appendChild(dummyDiv);` ``` then inshallowMount
attaching it: ``` wrapper = shallowMount(MapLeaflet, { attachTo: dummyDiv, localVue, store, stubs: { NuxtLink: RouterLinkStub, }, }); ```