2017-02-14 66 views
2

我有一個地圖格式爲SVG或PNG的自定義圖例。圖例始終位於左下角,但可能相當大(用戶可以將其關閉)。傳單上方彈出的傳單地圖

該地圖還有許多標記。每個標記都有一個工具提示,也可以是大型的。當鼠標懸停在標記上時,工具提示會顯示。當用戶懸停在靠近圖例的標記上時出現問題 - 工具提示出現在圖例後面。我想讓它出現在圖例上方。所以,從下到上:標記,圖例,標記彈出。

這裏是一個JSFiddle https://jsfiddle.net/e51mydwa/9/來描述我的意思。我以同樣的方式添加了傳說,儘管< div id =「legend」>標籤實際上包含< img或< svg>。

<div id="map"> 
    <div id="legend"> 
    I am Legend 
    </div> 
</div> 

我看了一下http://leafletjs.com/examples/choropleth/,但你可以通過檢查DOM看到,這將遭受同樣的問題,因爲傳說加入到同一div爲單張控制,這始終是在地圖圖層之上(因爲它應該是,控件應始終位於頂部)。

我也嘗試將圖例插入到包含彈出層的兄弟圖層上的div中。這解決了z-index問題,但是這兩者的父div包含一個隨用戶拖動地圖而變化的變換 - 這意味着圖例更改位置並且不是靜態的。

任何和所有建議表示讚賞。

回答

3

由於Leaflet圖層和控件的體系結構,這需要一些嚴重的黑客攻擊。

一種可能的方法是通過在每次更改地圖視圖時重新定位其像素偏移量來使自定義圖層類保持靜態位置。

我衷心推薦閱讀Leaflet tutorials,特別是關於地圖窗格和自定義圖層的文章,以瞭解其工作原理。

// Create a 'static' map pane 
L.Map.addInitHook(function(){ 
    this.createPane('static'); 
    this.getPane('static').style.zIndex = 675; 
}); 

// Define a custom layer class 
L.Layer.StaticOverlay = L.Layer.extend({ 
    onAdd: function(map) { 
    this._map = map; 

    var pane = map.getPane('static'); 
    this._container = L.DomUtil.create('div'); 

    pane.appendChild(this._container); 

    // styling, content, etc 
    this._container.style.background = 'white'; 
    this._container.style.width = '100px'; 
    this._container.style.height = '50px'; 
    this._container.innerHTML = 'Hi!' 


    map.on('move zoom viewreset zoomend moveend', this._update, this); 

    this._update(); 
    }, 

    onRemove: function(map) { 
    L.DomUtil.remove(this._container); 
    map.off('move zoom viewreset zoomend moveend', this._update, this); 
    }, 

    _update: function() { 
    // Calculate the offset of the top-left corner of the map, relative to 
    // the [0,0] coordinate of the DOM container for the map's main pane 

    var offset = map.containerPointToLayerPoint([0, 0]); 

    // Add some offset so our overlay appears more or less in the middle of the map 
    offset = offset.add([340, 220]); 

    L.DomUtil.setPosition(this._container, offset); 

    } 
}); 

這項步驟定義,你可以簡單地

var static = new L.Layer.StaticOverlay().addTo(map); 

顯然,有一些細節忽略了,比如如何覆蓋適當的定位(與getSize()獲取地圖像素大小,做適當的算術) ,以及如何使用圖層構造函數中的一些自定義選項設置疊加層的內容。

這些作爲練習留給讀者:-)

看到一個working example here

+0

嗨伊萬,謝謝你的幫助。看着這個工作的例子,這似乎正是我想要達到的目標,非常感謝。 –