javascript - 传单 : Map container is already initialized does not get solved by proposed answers

标签 javascript leaflet

我正在尝试使用传单加载 map 。当我刷新 map 时,出现上述错误。我研究了这个问题的其他建议答案。但是,他们中没有一个对我有用。 我正在尝试在由 onclick 事件运行的函数中加载 map 。这是代码:

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
}

经过测试的建议答案:
1- 检查我的 map 是否已初始化,如果是,请将其删除,然后重新定义。

console.log(mymap);
if(mymap != 'undefined' || mymap != null) {
 mymap.remove(); 
} 

结果:每当我刷新函数时,mymap 是未定义的,只是同样的错误。
2- 就在 mapdiv dom 准备就绪时,将此变量定义为函数外的通用变量。然后我使用了 jquery。

$( "#mapid" ).load(function() {
  var mymap= L.map('mapid');
});

结果:此错误:未找到 map 容器。
3- 删除 mydiv dom 并尝试在函数内部重新创建它。

console.log(mymap);
if(mymap != undefined || mymap != null){
    mymap.remove();
   $("#mapdiv").html("");
   $( "<div id=\"mapdiv\" style=\"height: 500px;\"></div>" ).appendTo(document);
}

结果:mymap未定义,只是代码没有运行来测试其效率。
任何想法或建议表示赞赏。谢谢。

最佳答案

我建议您需要在用于实例化 Leaflet map 的函数的外部范围内创建引用。比如你有一个函数

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
}

里面封装了mymap。执行此函数后,您将无法访问刚刚创建的 Leaflet 实例。在此函数范围之外对 mymap 的任何引用都将引用另一个变量。因此,我们的想法是将此变量保留在此函数的范围之外:

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
}

现在,您可以从定义此变量的范围内的任何地方引用 mymap。如果它是全局范围,那么您就不受限制。

接下来,做

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
}

看看它是否有效。

不要忘记,如果你在函数的外部作用域中声明了一个同名的新变量,它是一个具有新引用的新变量,因此你将无法再在外部作用域中引用该变量.所以要小心 vars。

关于javascript - 传单 : Map container is already initialized does not get solved by proposed answers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40825987/

相关文章:

javascript - 使用文本字段同时过滤 react 表和 react 传单标记(在表格中显示过滤数据,在 map 中显示标记)

javascript - 使用 _.some | _.any 正确表示破折号或下划线

javascript - setTimeout 不等待指定的毫秒数

javascript - 我可以在Flask中创建指向页面上特定项目的自定义链接吗?

html - 传单 map 不会在浏览器中呈现

jquery-tools - 使用 leaflet markercluster 插件时在单个标记上触发点击事件

单个域的 Javascript 文件

javascript - 单击时禁用 asp.net 按钮

jQuery on() 委托(delegate)事件和 Leaflet.js

javascript - 在传单上用 d3 覆盖圆圈会导致位置不正确