Uncaught error map container is already initialized

refreshing a leaflet map giving Error: Map Container Is Already Initialized

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

bibeputt opened this issue

Oct 24, 2015

· 24 comments

Comments

@bibeputt

refreshing a leaflet map giving Error: Map Container Is Already Initialized

@snkashis

Sounds like you are trying to re-init an existing map… The issues boards here is more for working through bugs and suggestions of new features. StackOverflow(http://stackoverflow.com/questions/tagged/leaflet) is a better place for troubleshooting your usage of the library. If you do believe this is from a bug, post your example case in a JSFiddle or another demo site.

@bibeputt

Looks like issue is related to implementation in MVVM and not a bug. Will try to search some MVVM examples using leaflet.

@ralexrdz

same issue here… what could it be?

@mourner

@ralexrdz perhaps a container that you initialize more than once?

@ralexrdz

@epicallan

i am having the same issue, i am using leaflet in React

@danzel

That’ll be a react-leaflet bug probably @epicallan

@epicallan

@danzel i am using react, its react-leaflet bug, just did some hacky work arounds

@srflorea

@epicallan Can you please explain what you did? I have the same issue with React and Leaflet.

@Dipinrajc

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get(‘map’);
if(container != null){
container._leaflet_id = null;
}

Thato-UTH, pawansaket, vuongducanh, trent-grunewald, fillipefeitosa, mohcinenazrhan, Pyligent, enzojimenez, SyedAkmal, dimitrisal, and 36 more reacted with thumbs up emoji
rafaltrojanowski, ottoperakyla, and vrkfx reacted with thumbs down emoji
pawansaket, Zohamo, rafaelcb21, MRVirus007, YUUKIToriyama, and JiuyingHan reacted with laugh emoji
SyedAkmal, rafaelcb21, MRVirus007, tozeos, JiuyingHan, 0rameez, and celsonyl reacted with hooray emoji

@adrielstar

@Dipinrajc With this method your not available to drag with mouse on the map.

fillipefeitosa, norzserge, miliariadnane, renzocastillo, Scemist, masoudnemati, born2discover, rishi-atidiv, feliking, nathanmichel, and 2 more reacted with thumbs up emoji

@fillipefeitosa

Any ideia how to drag map again with mouse @adrielstar ?

@adrielstar

I us this @fillipefeitosa .

HTML:
< div id=»map» >< /div>

render map:
document.getElementById(‘map’).innerHTML = «< div id=’map’ style=’width: 100%; height: 100%;’>»;

to reload content of div where render map.
Hoop this will help you too

@fillipefeitosa

Thanks friend, but that did not work. It replaced my var map with the div and map not loads

@enzojimenez

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get(‘map’);
if(container != null){
container._leaflet_id = null;
}

is there an existent leaflet method for this?

@mohafouad

@SyedAkmal

Before initializing map check for is the map is already initiated or not
var container = L.DomUtil.get(‘map’);
if(container != null){
container._leaflet_id = null;
}

is there an existent leaflet method for this?

@enzojimenez , You can create one method for this as I have created below

function initializingMap() // call this method before you initialize your map.
{
var container = L.DomUtil.get(‘map’);
if(container != null){
container._leaflet_id = null;
}
}

@josuelmm

@amin-setayeshfar

as said here, this would be the best way of doing it:
if (map != undefined) { map.remove(); }

@MRVirus007

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get(‘map’);
if(container != null){
container._leaflet_id = null;
}

You are an Angel

@Ashik-AD

Try this it might work

—-HTML—-

<div class="map-wrapper">
   <div id="map"><div>
</div>

—-JS——
//map-wrapper and map
const mapWrp = document.querySelector(‘.map-wrapper’);
const map = document.querySelector(‘#map’);

//Create a new map element
const newMap = document.createElement(‘div’);
newMap.setAttribute(‘id’, ‘map’);

// Remove older/previous map element
mapWrp.removeChild(map);

// insert new map element
mapWrp.append(newMap);

**Please insert this code before Actual map initialized**

@fillipefeitosa

@Ashik-AD ,

there is a time since I last messed up with this, but I certainly try and feedback to you. Thanks for your time

@kirklimbu

i was facing same issue as in Angular, i was using maps in two different components with same id

. I simply changed id and kept two separate ids and solved this issue.

@raulandrez

don’t use:

var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
    }).addTo(map);

use:

var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
    });
map.addLayer(osm);

Содержание

  1. Error: Map Container Is Already Initialized #3962
  2. Comments
  3. Uncaught Error: Map container is already initialized with React v18 and Formik #936
  4. Comments
  5. Bug report
  6. Expected behavior
  7. Actual behavior
  8. Steps to reproduce
  9. Error: Map container is already initialized. #7208
  10. Comments
  11. Footer

Error: Map Container Is Already Initialized #3962

refreshing a leaflet map giving Error: Map Container Is Already Initialized

The text was updated successfully, but these errors were encountered:

Sounds like you are trying to re-init an existing map. The issues boards here is more for working through bugs and suggestions of new features. StackOverflow(http://stackoverflow.com/questions/tagged/leaflet) is a better place for troubleshooting your usage of the library. If you do believe this is from a bug, post your example case in a JSFiddle or another demo site.

Looks like issue is related to implementation in MVVM and not a bug. Will try to search some MVVM examples using leaflet.

same issue here. what could it be?

@ralexrdz perhaps a container that you initialize more than once?

@mourner The html is basically html head loading js and css and a div with . And the only js that I have is
map.setView([19.34, -99.15], 12);
L.tileLayer(‘https://api.tiles.mapbox.com/v4////.png?access_token= ‘, <
attribution: ‘Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox’,
maxZoom: 18,
id: ‘mapboxMapId,
accessToken: ‘mapboxAccessToken’
>).addTo(map);
How could that be that a container is initialize before?

i am having the same issue, i am using leaflet in React

That’ll be a react-leaflet bug probably @epicallan

@danzel i am using react, its react-leaflet bug, just did some hacky work arounds

@epicallan Can you please explain what you did? I have the same issue with React and Leaflet.

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get(‘map’);
if(container != null) <
container._leaflet_id = null;
>

@Dipinrajc With this method your not available to drag with mouse on the map.

Any ideia how to drag map again with mouse @adrielstar ?

HTML:

render map:
document.getElementById(‘map’).innerHTML = » «;

to reload content of div where render map.
Hoop this will help you too

Thanks friend, but that did not work. It replaced my var map with the div and map not loads

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get(‘map’);
if(container != null) <
container._leaflet_id = null;
>

is there an existent leaflet method for this?

same problem with me 🙁

Before initializing map check for is the map is already initiated or not
var container = L.DomUtil.get(‘map’);
if(container != null) <
container._leaflet_id = null;
>

is there an existent leaflet method for this?

@enzojimenez , You can create one method for this as I have created below

function initializingMap() // call this method before you initialize your map.
<
var container = L.DomUtil.get(‘map’);
if(container != null) <
container._leaflet_id = null;
>
>

Para resolver el problema, define:
import * as Map from ‘leaflet’;

@ViewChild(‘map’) mapElement: ElementRef;
map: Map.Map;

this.map = Map.map(this.mapElement.nativeElement, <
maxZoom: 18
>);

as said here, this would be the best way of doing it:
if (map != undefined)

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get(‘map’);
if(container != null) <
container._leaflet_id = null;
>

You are an Angel

Try this it might work

—-JS——
//map-wrapper and map
const mapWrp = document.querySelector(‘.map-wrapper’);
const map = document.querySelector(‘#map’);

//Create a new map element
const newMap = document.createElement(‘div’);
newMap.setAttribute(‘id’, ‘map’);

// Remove older/previous map element
mapWrp.removeChild(map);

// insert new map element
mapWrp.append(newMap);

there is a time since I last messed up with this, but I certainly try and feedback to you. Thanks for your time

i was facing same issue as in Angular, i was using maps in two different components with same id

Источник

Uncaught Error: Map container is already initialized with React v18 and Formik #936

Bug report

  • All peer dependencies are installed: React, ReactDOM and Leaflet.
  • Using a supported version of React and ReactDOM (v17.0.0 minimum).
  • Using the supported version of Leaflet (v1.7.1 minimum) and its corresponding CSS file is loaded.
  • Using the latest v3 version of React-Leaflet.
  • The issue has not already been reported.
  • Make sure you have followed the quick start guide for Leaflet.
  • Make sure you have fully read the documentation and that you understand the limitations.

I understand that I have reported bug using React v18 RC version that has not been released yet, but I believe this will soon be raised anyway. If I have missed any posts regarding supporting React v18 — I apologise in advance

  • React v18.0.0-rc.0-next-ceee524a8-20211217 ,
  • ReactDOM v8.0.0-rc.0-next-ceee524a8-20211217,
  • Formik v2.2.9;

Using React v18 style createRoot + render API (reactwg/react-18#5) and with using library Formik (https://github.com/jaredpalmer/formik) it is possible to catch moment when inside useMapElement hook mapRef.current is set, map is still null at the if statement,

but when next instruction starts executing const instance = new LeafletMap(mapRef.current, props); map has been set, therefore this error happens:

This looks like an issue that could be related to Reacts v18 New root API:

State variable map mutates within function execution.

This issue is not present if using old API ReactDOM.render .

Expected behavior

When navigating using BrowserRouter NavLink to component with map it is expected to render map without error.

Actual behavior

When navigating using BrowserRouter NavLink to component with map — error happens.

But if you navigate to specific page url directly with refresh — then it always work.
Go away from page with map and come back — error happens.

Steps to reproduce

I did not manage to setup example in code pen (I apologise again),
this is the shortest reproducible example I come up with:

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Error: Map container is already initialized. #7208

Dear friends, I am testing the map using a recursive function to simulate a real-time update of a marker’s map. I tried to search for all the alternatives in the forums but I didn’t find anything that really worked and, every time I run the html file, I have the following error: Map container is already initialized.

Below is the code I’m testing:

The text was updated successfully, but these errors were encountered:

Hi, great to hear that you find Leaflet useful!

However, this issue tracker is used for reporting bugs and discussing new features. For questions on using Leaflet, please use gis.stackexchange.com or stackoverflow.

If you are really sure that this is a bug in leaflet, or a feature request, please change the wording to make it look like a bug report.

If Leaflet tells you «Map container is already initialized.», then it means that you’re initializing a map in a container when a leaflet map already exists in that container. Do L.map(‘location-map’) once instead.

Thanks for your feedback. I understand your point here. But in my use case I have an initialized Map with drawing controls and so on and at certain point of time the user can trigger «routing». So I’m expecting to use something like this :
L.tripgoRouting.initialize(options).addto(mymap); or .addcontrol(L.tripgoRouting(options))
Unfortunatly, this not the case in TripgoRouting.js

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Answer by Jaylah Allen

where <div id=»map-canvas»></div> is the object the map has been drawn into.,Without document.getElementById(‘mapLayer’).innerHTML = «» the map was not displayed on the next page. ,

(optional) marker in cppreference.com documentation

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>";

Answer by Rosalia Macdonald

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
}

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
}

Answer by Dani Gallegos

On first run map works great.but after switching tabs and going back to map tab,i have map container is already initialized error.tried ionviewcanleave to make map html empty but seems like its not working.

import { Component,ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import leaflet from 'leaflet';


@Component({
  selector: 'page-map',
  templateUrl: 'map.html'
})
export class MapPage {

  @ViewChild('map') mapContainer: ElementRef;
  map: any;

  constructor(public navCtrl: NavController) {


  }

  ionViewDidEnter() {
    this.loadmap();
  }
  loadmap() {

    this.map = leaflet.map("map").fitWorld();
    leaflet.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attributions: 'www.tphangout.com',
      maxZoom: 18
    }).addTo(this.map);
    this.map.locate({
        setView: true,
        maxZoom: 10
      }).on('locationfound', (e) => {
        let markerGroup = leaflet.featureGroup();
      let marker: any = leaflet.marker([e.latitude, e.longitude]).on('click', () => {
        marker.bindPopup("selam").openPopup();
      })
      markerGroup.addLayer(marker);
      this.map.addLayer(markerGroup);
      }).on('locationerror', (err) => {
        alert(err.message);
    })

  }
  ionViewCanLeave(){
document.getElementById("map").outerHTML = "";
}

}

Answer by Jakobe Rogers

I just use the following line at the top of each of my controllers:

$scope.map = L.map('myMapDiv');

For each view/controller, I have a different map <DIV> name, i.e.

$scope.map = L.map('mapDivOne');  // Controller 1

$scope.map = L.map('mapDivTwo'); // Controller 2

I even tried:

if (!$scope.map) {
  $scope.map = L.map('commonMap');
}

Answer by Louisa Moss

i have 2 tabs in ionic app tab1–> map , tab2 –> some other page when i click on tab1 and go to tab 2 and after some time if click on tab1 again i am getting error as
Map container is already initialized
,if i am tab1 and going to tab2 and again clicking on the tab1 if pinch n zoom the maps tiles are going back wards and clearing map images and showing grey area.
,Here i am trying to display the leaflet js maps in ionic 5 tabs below are my issues

html

<ion-content id="mapId" style="--offset-top:0px; --offset-bottom:0px;">
</ion-content>

 // when ever a marker on map is clicked then the this below ionic content will displayed 
<ion-content class="detail-desc" id="detail-desc">  
</ion-content>

map: L.Map;
center: L.PointTuple;

leafletMap() {
    document.getElementById('detail-desc').style.display = 'none';

    this.map = L.map('mapId').setView([this.Latitude, this.Longitude], 20);
    L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map);

    const myFeatureGroup = L.featureGroup().addTo(this.map).on('click', (e) => {
      console.log(e);
      const event = e;
      const that = this;
      this.myTest(event, that);
    });
    let marker: any;

    const availableIcon = L.icon({
      iconUrl: '../../assets/icon/marker-icon-2x.png',


      iconSize: [21, 34],
    });
    const unAvailableIcon = L.icon({
      iconUrl: '../../assets/icon/marker-icon-red.png',
   

      iconSize: [21, 34], 
    });
  

    const locationIcon = L.icon({
      iconUrl: '../../assets/icon/current-location.png',
 

      iconSize: [30, 30], 
    });
    
    marker = L.marker([this.Latitude, this.Longitude], { icon: locationIcon }).addTo(myFeatureGroup);
   
    for (let i = 0; i < this.mapData.length; i++) {
      if (this.mapData[i].status === 'Available') {
        marker = L.marker([this.mapData[i].locationLat, this.mapData[i].locationLong],{ icon: availableIcon ,id:this.mapData[i].Id}).addTo(myFeatureGroup);
      } else {
        marker = L.marker([this.mapData[i].locationLat, this.mapData[i].locationLong],{ icon: unAvailableIcon,id:this.mapData[i].Id }).addTo(myFeatureGroup);
      }

      marker.selectedData = this.mapData[i];
    }


  }

Answer by Zeke Wood

refreshing a leaflet map giving Error: Map Container Is Already Initialized,Para resolver el problema, define:
import * as Map from ‘leaflet’;,is there an existent leaflet method for this?

<div class="map-wrapper">
   <div id="map"><div>
</div>

Answer by Curtis Roberts

btw, I’ve tried to destroy and recreate $(‘#mapa’) with jQuery before the second setView() but it shows the same error.,then use below line to refresh the map, but make sure to use same latitude, longitude and zoom options,For refreshing map in same page you can use below code to create a map on the page

The problem line is:

var map = L.map('mapa').setView([lat, lon], 15);

Answer by Seth Myers

Hi All,
I hope this is the right place to ask this question:,I have just installed leaflet/cloudmap for the first time and while the map appears to works as it should, I get the error that “Map container is already initialized.
(7 out of range 4),”,Having searched on the web, some people say that the map div is being created twice (I couldn’t see this myself).

Much appreciated!

    <script src="leaflet/dist/leaflet.js"></script>

    <div id="map" style="height: 200px"> <a href="#" data-role="button" id="getLocation">Get my location</a> </div>

    <script>

            $('#getLocation').click(function(){

            map = new L.Map('map');

            var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/myapikey/997/256/{z}/{x}/{y}.png',
            cloudmadeAttribution = 'Map data &copy; 2011 OpenStreetMap contributors, Imagery &copy; 2011 CloudMade',
            cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18, attribution: cloudmadeAttribution});
            map.setView(new L.LatLng(51.505, -0.09), 13).addLayer(cloudmade);

            var markerLocation = new L.LatLng(51.5, -0.09),
            marker = new L.Marker(markerLocation);
            map.addLayer(marker);
            marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();

            });

Answer by Oaklynn Morse

This tutorial uses the Mapbox GL JS Geocoder plugin.,To create the local search app, you will create an HTML file and initialize the map. Then you will add the Mapbox GL JS Geocoder plugin and set the bbox and proximity parameters.,Mapbox GL JS Geocoder

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title>Demo: Local search with the Geocoding API</title><meta name="viewport" content="width=device-width, initial-scale=1" /><script src="https://api.tiles.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.js"></script><linkhref="https://api.tiles.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.css"rel="stylesheet"/><script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.0/mapbox-gl-geocoder.min.js"></script><linkrel="stylesheet"href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.0/mapbox-gl-geocoder.css"type="text/css"/><style>body {margin: 0;padding: 0;}#map {position: absolute;top: 0;bottom: 0;width: 100%;}</style></head><body><div id="map"></div> <script>mapboxgl.accessToken = '<your access token here>';var map = new mapboxgl.Map({container: 'map', // Container IDstyle: 'mapbox://styles/mapbox/streets-v11', // Map style to usecenter: [-122.25948, 37.87221], // Starting position [lng, lat]zoom: 12 // Starting zoom level}); var marker = new mapboxgl.Marker() // Initialize a new marker.setLngLat([-122.25948, 37.87221]) // Marker [lng, lat] coordinates.addTo(map); // Add the marker to the map var geocoder = new MapboxGeocoder({// Initialize the geocoderaccessToken: mapboxgl.accessToken, // Set the access tokenmapboxgl: mapboxgl, // Set the mapbox-gl instancemarker: false, // Do not use the default marker styleplaceholder: 'Search for places in Berkeley', // Placeholder text for the search barbbox: [-122.30937, 37.84214, -122.23715, 37.89838], // Boundary for Berkeleyproximity: {longitude: -122.25948,latitude: 37.87221} // Coordinates of UC Berkeley}); // Add the geocoder to the mapmap.addControl(geocoder); // After the map style has loaded on the page,// add a source layer and default styling for a single pointmap.on('load', function () {map.addSource('single-point', {'type': 'geojson','data': {'type': 'FeatureCollection','features': []}}); map.addLayer({'id': 'point','source': 'single-point','type': 'circle','paint': {'circle-radius': 10,'circle-color': '#448ee4'}}); // Listen for the `result` event from the Geocoder // `result` event is triggered when a user makes a selection//  Add a marker at the result's coordinatesgeocoder.on('result', function (e) {map.getSource('single-point').setData(e.result.geometry);});});</script></body></html>

Answer by Kalel Diaz

Search Answer Titles


Понравилась статья? Поделить с друзьями:
  • Uncaught error invalidstateerror the connection has not been established yet
  • Uncaught error class memcache not found in
  • Uncaught error injector modulerr
  • Uncaught error extension context invalidated
  • Uncaught error expected the reducer to be a function