由於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。
嗨伊萬,謝謝你的幫助。看着這個工作的例子,這似乎正是我想要達到的目標,非常感謝。 –