百度地图中添加全屏控件
前置知识:
进入整个页面的全屏模式 :document.documentElement.requestFullscreen()
进入特定元素的全屏模式 : document.getElementById("ID").requestFullscreen()
退出全屏:document.exitFullscreen()
调用百度地图API写自定义控件的核心部分代码:
var map = new BMapGL.Map('map'); // 创建Map实例map.centerAndZoom(new BMapGL.Point(lng, lat), 3); // 初始化地图,设置中心点坐标和地图级别map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放var scaleCtrl = new BMapGL.ScaleControl(); // 添加比例尺控件map.addControl(scaleCtrl);var zoomCtrl = new BMapGL.ZoomControl(); // 添加缩放控件map.addControl(zoomCtrl);// 添加自定义全屏控件 定义 一个控件类function ZoomControl() {this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;this.defaultOffset = new BMapGL.Size(10, 20)}//通过JavaScript的prototype属性继承于BMap.ControlZoomControl.prototype = new BMapGL.Control();//自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回ZoomControl.prototype.initialize = function (map) {//创建一个dom元素var div = document.createElement('div');//添加文字说明div.appendChild(document.createTextNode('全屏'));// 设置样式div.style.cursor = "pointer";div.style.padding = "8px 13px";div.style.margin = "20px 0px";div.style.boxShadow = "0 2px 6px 0 rgba(27, 142, 236, 0.5)";div.style.borderRadius = "5px";div.style.backgroundColor = "white";// 绑定事件-全屏div.onclick = function (e) {if (document.fullscreenElement === null){document.getElementById("map").requestFullscreen();}else {document.exitFullscreen();}}document.addEventListener("fullscreenchange", () => {if (document.fullscreenElement === null) {console.log("Exited fullscreen");div.innerText = '全屏';} else {div.innerText='退出全屏';console.log("Entered fullscreen");}});// 添加DOM元素到地图中map.getContainer().appendChild(div);// 将DOM元素返回return div;}//创建控件元素var myZoomCtrl = new ZoomControl();//添加到地图中map.addControl(myZoomCtrl);
效果: