openlayers2自帶圖層開關控件,但是自openlayers3後,不再有這個控件。但是,當了解了openlayers控件開發後,我們可以自己實現這個控件,實現起來也非常之簡單。不多說,先看下結果:
1、目標
1)圖層開關: 在控件上選中圖層,對應的圖層顯示;取消選中,對應的圖層關閉;
2)圖層增刪聯動: 當map中的圖層有增刪時,控件隨之改動。
2、控件開發
1)繼承
圖層開關控件類:ol.control.LayerSwitch
父類:ol.control.Control
ol.control.LayerSwitch = function(opt_options){
var options = opt_options ? opt_options : {};
this.element = document.createElement('div');
var defaultControlClassName = 'ol-unselectable ol-control';
var className = 'ol-control-layerswitch';
this.element.className = defaultControlClassName + ' ' + className;
ol.control.Control.call(this, {
element: this.element,
target: options.target
})
}
ol.inherits(ol.control.LayerSwitch, ol.control.Control);
2)控件屬性
主要有三給屬性
1、初始化控件:用來實現控件初始化時的UI設置;
2、增加圖層選項:添加圖層時自動觸發
3、移除圖層選項:移除圖層時自動觸發
初始化:
ol.control.LayerSwitch.prototype.init = function(){
var layers = this.getMap().getLayers();
layers.forEach(element => {
this.addLayerItem(element);
});
}
增加圖層選項:
/**
* 添加選項
* @param {ol.layer.Layer} layer
*/
ol.control.LayerSwitch.prototype.addLayerItem = function(layer){
var div = document.createElement('div');
div.className = 'ol-control-layerswitch-opt';
div.setAttribute('layerid', ol.getUid(layer).toString());
var child = document.createElement('input');
child.setAttribute('type', 'checkbox');
child.onclick = function(evt){
layer.setVisible(evt.target.checked);
};
child.checked = true;
div.appendChild(child);
var label = document.createElement('span');
label.innerText = layer.get('title');//以圖層的title屬性作爲顯示內容
div.appendChild(label);
this.element.appendChild(div);
}
移除圖層選項:
/**
* 移除選項
* @param {ol.layer.Layer} layer
*/
ol.control.LayerSwitch.prototype.removeLayerItem = function(layer){
var childs = this.element.getElementsByClassName('ol-control-layerswitch-opt')
for (let index = 0; index < childs.length; index++) {
const divChild = childs[index];
if(divChild.getAttribute('layerid') === ol.getUid(layer).toString()){
this.element.removeChild(divChild);
}
}
}
3、示例
4、存在的問題
ol.getUid(layer)報錯
添加或者增刪圖層時,用ol.getUid(layer)來獲取到圖層的ID,作爲唯一標識,但是發現引用ttps://openlayers.org/en/v4.6.5/build/ol.js這個js時,ol沒有這個方法,在官網API中也沒找到。但是引用下載到本地的openlayers的v.4.6.5版本中的ol-debug.js,是可以的。
openlayers5中ol已經增加了gitUid方法。
完整代碼就示例見:《openlayers圖層開關控件》