2016-11-27 20 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

相關問題