2016-11-27 21 views
2

我想通过使用小册子加载地图。当我刷新地图时,出现上述错误。我研究了这个问题的其他建议答案。但是,他们中没有人为我工作。 我正尝试在由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未定义,只是代码没有运行来测试其效率。
任何想法或建议表示赞赏。谢谢。

回答

3

我有一个建议,你需要在你用来实例化一个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 
} 

,看看它是否工作。

不要忘记,如果你声明一个新变量的名称与外部函数的作用域相同,那么它是一个带有新引用的新变量,所以你将无法引用外部变量中的变量了。所以要小心var s。

+0

谢谢你,干净,正确。 – keloniton

相关问题