openlayer实现图层控件功能

/**
 * 该文件用于添加图层控件功能
 * @author Wilson.Yan
 * @version 2016.8.18
 */
function layerCtrl(map){ //在外部调用
	//图层变动使用
	var group = map.getLayers();
	loadLayerControl(map,"layerTree");//第一次载入图层控件
	group.on('change:length',function(){ //响应事件:图层长度变化时发生
		loadLayerControl(map,"layerTree");//载入图层控件
	});
}

//内部调用
function loadLayerControl(maps,id){
	var layer = new Array(); //记录图层
	var layerName = new Array(); //记录图层名
	var layerVisibility = new Array(); //记录可视性
	var treeContent = document.getElementById(id); //读取图层表
	var layers = map.getLayers(); //读取所有图层
	$(treeContent).children("li").remove();//清除所有li
	for(var i=0;i<layers.getLength();i++){
		layer[i] = layers.item(i);
		layerName[i] = layer[i].get('name');
		layerVisibility[i] = layer[i].getVisible();
		
		//创建空图层项
		var li = document.createElement('li');
		treeContent.appendChild(li);
		
		//添加复选框
		var input = document.createElement('input');
		input.type = "checkbox";
		input.name = "layers";
		li.appendChild(input);
		
		//添加label
		var label = document.createElement('label');
		label.className = "layer";
		setInnerText(label,layerName[i]);
		li.appendChild(label);
		
		if(layerVisibility[i]){input.checked = true;}
		addChangeEvent(input,layer[i]);
	}
}
//内部调用	
	function addChangeEvent(element,layer){ //设置勾选事件的函数
		element.onclick = function(){
			if(element.checked){
				layer.setVisible(true);
			}
			else{
				layer.setVisible(false);
			}
		};
	}
//内部调用	
	function setInnerText(element,text){ 
		if(typeof element.textContent == "string"){
			element.textContent = text;
		}
		else{
			element.innerText = text;
		}
	}

转载自:https://blog.csdn.net/u013323965/article/details/52242537

You may also like...