【问题标题】:leaflet : Map container is already initialized does not get solved by proposed answers传单:地图容器已经初始化并没有通过建议的答案得到解决
【发布时间】:2022-01-09 08:35:57
【问题描述】:

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

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- 检查我的地图是否已初始化,如果是,请将其删除,然后再次定义。

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

结果:每当我刷新函数时,mymap 都是未定义的,只是同样的错误。
2- 仅当 mapdiv dom 准备好时,将此变量定义为函数之外的一般变量。然后我用jquery。

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

结果:此错误:未找到地图容器。
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 未定义,只是代码尚未运行以测试其效率。
任何想法或建议表示赞赏。谢谢。

【问题讨论】:

    标签: javascript leaflet


    【解决方案1】:

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

    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。

    【讨论】:

    • mymap !== undefined || mymap !== null 不会总是返回 true 吗?
    • 不错的收获。这是一个错字,我打算改用&amp;&amp;,所以现在已经修复了。回想起来,我认为整体代码可以改进很多。如果您有任何建议,请随时编辑。
    【解决方案2】:

    https://designlimbo.com/leaflet-ionic-3-and-map-container-is-already-initialized/

    通过 SO 和 Google 挖掘了几个小时,发现上述方法是唯一可靠工作的方法。不要乱用 remove() 或 off()。

    稍微摆弄ViewChild / ViewChildren 以获取 DOM 引用,但无论页面如何转换,我的所有地图都能可靠地加载到任何页面上。

    【讨论】:

    • 此页面不再可用(503 服务不可用)。本质是您通过 viewchild 查询包含传单地图的 div 并且您手动将其从 HTML 中删除,例如leafletDiv.remove() ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多