refresh leaflet map: map container is already initialized
Html:
<div id="weathermap"></div>
JavaScript:
function buildMap(lat,lon) {
document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttribution = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,' +
' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
var map = new L.Map('map');
map.setView(new L.LatLng(lat,lon), 9 );
map.addLayer(osmLayer);
var validatorsLayer = new OsmJs.Weather.LeafletLayer({lang: 'en'});
map.addLayer(validatorsLayer);
}
I use this:
document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
to reload content of div where render map.
leaflet : Map container is already initialized does not get solved by proposed answers
I have a suggestion that you need to create a reference in outer scope of a function you use to instantiate a Leaflet map. For example, you have a function
function load_map_and_analyze_data(){
var mymap = L.map('mapid',{ center: new L.LatLng(the_center_splitted[0],the_center_splitted[1]),maxZoom: 17, minZoom:11, zoom: 14}); //creating the map
//the rest of analyze and code goes here
}
that encapsulates mymap
in it. After you execute this function, you have no chance to access the instance of Leaflet you just created. Any reference to mymap
outside of this function's scope will refer to another variable. So, the idea is to keep this variable outside of the scope of this function:
var mymap = null;
function load_map_and_analyze_data() {
mymap = L.map('mapid',{ center: new L.LatLng(the_center_splitted[0],the_center_splitted[1]),maxZoom: 17, minZoom:11, zoom: 14}); //creating the map
//the rest of analyze and code goes here
}
Now, you can refer to mymap
from anywhere within the scope this variable is defined. If it is the global scope, then you're not limited in it.
Next, do
console.log(mymap); // should output the object that represents instance of Leaflet
if (mymap !== undefined && mymap !== null) {
mymap.remove(); // should remove the map from UI and clean the inner children of DOM element
console.log(mymap); // nothing should actually happen to the value of mymap
}
and see if it works.
Don't forget that if you declare a new variable with the same name as in outer scope of a function, it's a new variable with a new reference, so you will not be able to refer to the variable in outer scope anymore. So be careful with var
s.
jQuery and Leaflet gives error "map container is already initialized"
You're on the right lines, but you should remove()
the map before you (re)-initialize it - and make sure the scope of the map
variable is correct. Like this
var map;
...
function initMap(actramp, actimpdel, actexpreceipt, actramplat, actramplng, actreclat,
actreclng, actdellat, actdellng)
{
if (map != undefined) map.remove();
map = L.map('map').setView([actreclat,actreclng], 8);
...
}
Leaflet map: map container is already initialized
L.map('map')
initializes a Leaflet map using the given element id. You cannot call this twice for the same element.
const attribution = document.querySelector("#attribution").innerHTML;
const mymap = L.map("map").setView([0, 0], 0);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution })
.addTo(mymap);
L.map("mymap"); // <- error, the map is already initalized
#map { height: 70px; }
<link crossorigin rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script crossorigin src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<div id="map"></div>
<template id="attribution">
©
<a href="https://www.openstreetmap.org/copyright">
OpenStreetMap
</a>
contributors
</template>
Uncaught Error: Map container is already initialized
It seems an important question to me. Hence, answering here for sake of completeness. This is based on this link shared by @Satya S in the comments. React leaflet v3 won't work with reactJS v18 (as of the time of writing this response, things may change later. Use this link to verify), at least when using concurrent mode.
Please try version 4 alpha of React leaflet that targets version 18 of reactJS.
React/Leaflet-side-by-side Error: Map container is already initialized. #35
This is happening because on mount, L.map
is finding <div id="map" />
and initializing it to be a map. Then whenever your useEffect
runs, it is trying to use that same div to run L.map
again, but leaflet recognizes that that div is already a leaflet map, so it errors.
I recommend using actual react-lealfet components:
import { MapContainer, TileLayer } from 'react-leaflet';
const MyComponent = () => {
const [baseViewCoords, setBaseViewCoords] = useState([37.715, 44.8611]);
const [map, setMap] = useState();
const searchApiHandler = () => {...};
useEffect(() => {
if (map){
L.control.sideBySide(stamenLayer, osmLayer).addTo(map);
}
}, [map])
useEffect(() => {
if (map){
map.setView(baseViewCoords)
}
}, [map, baseViewCoords]);
return (
<MapContainer
center={baseViewCoords}
zoom={13}
whenCreated={map => setMap(map)}
>
<TileLayer
url={osm_url}
/>
<TileLayer
url={stamen_url}
/>
</MapContainer>
)
}
Related Topics
Validate Phone Number With Yup
React Router Dom Returns a Blank Page When Going to a Particular Route
Check If a Number Has Repeated Digits
If a Div Contains a Specific String of Text, Edit the Parent'S CSS
Get Part of the Url Pathname Via JavaScript Regex
Eslint: Disable Warning - 'Defined But Never Used' for Specific Function
Javascript Innerhtml Not Updating Element
In Nest.Js, How to Get a Service Instance Inside a Decorator
Json to CSV Flattening Nested Json
How to Determine Server Disconnection from Signalr Client
Jquery Click Events Firing Multiple Times
Bootstrap 4 Display Dropdown Submenu on the Right Side
Webcam Js Error in Chrome: Could Not Access Webcam
How to Take Screenshot of a Div With JavaScript
How to Print Image from Browser Using JavaScript
Nodejs MySQL Get Correct Timestamp Format