2017-03-09 44 views
0

我希望用戶能夠快速切換到側邊欄中的功能。當點擊邊欄中的特定div時,我希望該div移動到主區域中,並在主區域中移動到邊欄(交換內容)。因此,我實現了一個JavaScript函數,可以交換這些div的css類和DOM位置。在DOM操作後清空OpenLayers畫布

var node1 = document.querySelector(".one"); 
var node2 = document.querySelector(".other"); 
node1.classList.toggle("other"); 
node1.classList.toggle("one"); 
node2.classList.toggle("one"); 
node2.classList.toggle("other"); 
var clone1 = node1.cloneNode(true); 
var clone2 = node2.cloneNode(true); 
node2.parentNode.replaceChild(clone1, node2); 
node1.parentNode.replaceChild(clone2, node1); 

工作正常,例如與在divs中的圖片。如果我將一個簡單的OpenLayers地圖放入其中一個div,它將顯示它應該顯示的內容,直到我點擊並交換地圖(無論是進入主區域還是側邊欄)。在空的畫布上,我只能看到控件和屬性按鈕(至少後者不起作用)。

"use_strict"; 
var Map = {}; 
Map.locationLonLat = [0, 51.477222]; 
Map.zoom = 15; 

Map.initMap = function() { 
    var map = new ol.Map({ 
     target: "map", 
     layers: [ 
      new ol.layer.Tile({ 
       source: new ol.source.OSM(), 
       alpha: true, 
       isBaseLayer: true, 
      }), 
     ], 
     view: new ol.View({ 
      center: new ol.proj.fromLonLat(Map.locationLonLat), 
      zoom: Map.zoom, 
     }), 
    }); 
} 

雖然所有我可能需要的是一個地圖刷新(我嘗試了一些的#2提供的,如刷新的方法,重新繪製,渲染,updateSize等),我也試過初始化地圖再次(如我原本是) - 無濟於事。

<div class="sidebar" onclick="Util.swapNodes(event); Map.initMap();"> 

任何想法這裏發生了什麼?

回答

0

好吧,搞定了。關鍵是要做兩件事:

首先,我必須從OperLayers生成的div中清除DOM,該div包含地圖及其按鈕(並且可能是對不同DOM位置的「舊」地圖的引用);其類是ol-viewport。第二,交換節點後(如上面的代碼所示),我還必須更改映射節點的ID;否則,我們不得不更改映射節點的ID。至少我沒有找到直接「刷新」舊ID的方法。

所以,我所做的就是這樣的:

var mapNode = document.querySelector(".map"); // finds the class 
if (mapNode.parentNode.classList.contains("one")) { 
    mapNode.id = "mapone"; // change the id 
    document.querySelector(".ol-viewport").remove(); // remove old div 
    map.setTarget("mapone"); // re-set target to new id 
} else if (mapNode.parentNode.classList.contains("other")) { 
    mapNode.id = ("mapother"); // change the id 
    document.querySelector(".ol-viewport").remove(); // remove old div 
    map.setTarget("mapother"); // re-set target to new id 
}