OpenLayers 设置图层透明度

发布于:2025-06-20 ⋅ 阅读:(9) ⋅ 点赞:(0)

注:当前使用的是 ol 9.2.4 版本,天地图使用的key请到天地图官网申请,并替换为自己的key

加载到地图中的图层具有图层名、分辨率、坐标系等属性,可以获取和设置图层属性来更好的辅助开发工作,本节主要介绍获取和设置图层透明度属性。

1. 获取图层列表

通过map方法getLayers()获取图层列表,然后调用getArray()将其转换为图层数组。getProperties()方法可以获取图层属性,从而构建图层树。绑定data-title属性,方便过滤目标图层。添加图层属性图标点击事件setLayerProp

const layers = map.getLayers().getArray()
const formEle = document.querySelector(".layer-form")
layers.forEach(layer => {
    const props = layer.getProperties()
    // console.log("props:", props)
    const layerTitle = `<label class="layui-form-label">
        ${props.title}
        <i class="layui-icon layui-icon-set-fill layui-icon-custome" data-title="${props.title}" onclick="setLayerProp(event)"></i>
        </label>`
    formEle.innerHTML += layerTitle
});

2. 设置图层透明度

解构dataset属性值title,获取目标涂层。通过layui绑定透明度滑块,并监听透明度change事件当滑块值改变时,获取滑块值并设置图层透明度。

const layerPropEle = document.querySelector(".layer-prop-set")
function setLayerProp(event) {
    layerPropEle.style.display = "block"
    const { title } = event.target.dataset
    const propEle = `
        <h3>${title}</h3>
        <div class='layer-prop-item'>
            <label class="layui-label">透明度:</label>
            <div class="layer-slider-item" id="transparent-prop"></div>
        </div>`
    layerPropEle.innerHTML = propEle

    // 查找目标图层
    const targetLayer = layers.find(layer => layer.getProperties().title === title)
    layui.use(function () {
        const slider = layui.slider;
        // 渲染
        slider.render({
            elem: '#transparent-prop',
            step: 0.1, // 步长
            min: 0,
            max: 1,
            value: targetLayer.getOpacity(),
            change: function (value) {
                console.log(value) // 滑块当前值
                targetLayer.setOpacity(value)
            }
        })
    });
}

3. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。本示例引用了layui组件,请自行替换。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>图层透明度属性</title>
    <meta charset="utf-8" />
    <script src="../../libs/js/jquery-2.1.1.min.js"></script>
    <script src="../../libs/proj4.js"></script>
    <script src="../../js/ol9.2.4.js"></script>
    <script src="../../libs/layui/layui.js"></script>

    <link rel="stylesheet" href="../../css/ol9.2.4.css">
    <link rel="stylesheet" href="../../libs/layui/css/layui.css">
    <style>
        * {
            padding: 0;
            margin: 0;
            font-size: 14px;
            font-family: '微软雅黑';
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        #map {
            position: absolute;
            top: 50px;
            bottom: 0;
            width: 100%;
        }

        #top-content {
            position: absolute;
            width: 100%;
            height: 50px;
            line-height: 50px;
            background: linear-gradient(135deg, #ff00cc, #ffcc00, #00ffcc, #ff0066);
            color: #fff;
            text-align: center;
            font-size: 32px;
        }

        #top-content span {
            font-size: 32px;
        }

        #layer-container {
            position: absolute;
            top: 15%;
            left: 20px;
            width: 20%;
            bottom: 5%;
            background: #fff;
            color: #fff;
            border: 1px solid #ddd;
            border-radius: 2.5px;
        }

        .layer-head {
            background: #16baaa;
            padding: 10px;
            margin-bottom: 15px;
        }

        .layer-form {
            padding: 0 10px;
        }

        .layui-form-label {
            width: 100%;
            padding: 8px 15px;
            height: 38px;
            line-height: 20px;
            border-width: 1px;
            border-style: solid;
            border-radius: 2px 0 0 2px;
            text-align: center;
            background-color: #fafafa;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            box-sizing: border-box;
            border-color: #eee;
            font-weight: 400;
            color: #000;
        }

        .layui-icon-custome {
            color: #ccc;
        }

        .layui-icon-custome:hover {
            cursor: pointer;
            color: #1E9FFF;
        }

        .layer-prop-set {
            display: none;
            position: absolute;
            padding: 10px;
            margin-top: 120px;
            margin-left: 345px;
            width: 250px;
            background: #fff;
            border-radius: 5px;
            box-shadow: 5px 6px 6px 2px #d3d3d3;
        }

        .layer-prop-item {
            display: flex;
            justify-content: space-between;
            flex-direction: row;
            margin: 10px 0;

        }

        .layer-slider-item {
            width: 70%;
            margin-top: 7px;
        }
    </style>
</head>

<body>
    <div id="top-content">
        <span>图层属性设置</span>
    </div>
    <div id="map" title="地图显示"></div>
    <div id="layer-container">
        <h2 class="layer-head">图层设置</h2>
        <div class="layer-form">

        </div>
    </div>
    <div class="layer-prop-set">

    </div>
</body>

</html>

<script>

    //地图投影坐标系
    const projection = ol.proj.get('EPSG:3857');
    //==============================================================================//
    //============================天地图服务参数简单介绍==============================//
    //================================vec:矢量图层==================================//
    //================================img:影像图层==================================//
    //================================cva:注记图层==================================//
    //======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================//
    //==============================================================================//
    const TDTImgLayer = new ol.layer.Tile({
        title: "天地图影像图层",
        source: new ol.source.XYZ({
            url: "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=",
            attibutions: "天地图影像",
            crossOrigin: "anoymous",
            wrapX: false
        })
    })
    const TDTCvaLayer = new ol.layer.Tile({
        title: "天地图注记图层",
        source: new ol.source.XYZ({
            url: "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=",
            attibutions: "天地图注记",
            crossOrigin: "anoymous",
            wrapX: false
        })
    })
    const TDTVecLayer = new ol.layer.Tile({
        title: "天地图矢量图层",
        source: new ol.source.XYZ({
            url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=",
            attibutions: "天地图矢量",
            crossOrigin: "anoymous",
            wrapX: false
        })
    })
    const map = new ol.Map({
        target: "map",
        loadTilesWhileInteracting: true,
        view: new ol.View({
            center: [104.0635986160487, 30.660919181071225],
            zoom: 5,
            worldsWrap: false,
            minZoom: 1,
            maxZoom: 20,
            projection: "EPSG:4326"
        }),
        layers: [TDTImgLayer, TDTCvaLayer, TDTVecLayer],
        // 地图默认控件
        controls: ol.control.defaults.defaults({
            zoom: false,
            attribution: true,
            rotate: true
        })
    })
    map.on('click', evt => {
        console.log(evt.coordinate)
    })

    // 添加矩形
    const rectangle = new ol.layer.Vector({
        title: "矩形",
        source: new ol.source.Vector({
            features: [
                new ol.Feature({
                    geometry: new ol.geom.Polygon([
                        [
                            [95.0635986160487, 30.660919181071225],
                            [104.0935986160487, 30.660919181071225],
                            [104.0935986160487, 26.060919181071225],
                            [95.0635986160487, 26.060919181071225],
                            // [104.0635986160487, 30.660919181071225]
                        ]
                    ])
                })
            ]
        }),
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: "#16baaab0"
            }),
            stroke: new ol.style.Stroke({
                color: "#1e9fff"
            })
        })
    })

    // 添加三角形
    const triangle = new ol.layer.Vector({
        title: "三角形",
        source: new ol.source.Vector({
            features: [
                new ol.Feature({
                    geometry: new ol.geom.Polygon([
                        [
                            [96.0635986160487, 33.760919181071225],
                            [104.0935986160487, 30.660919181071225],
                            [99.5785986160487, 23.660919181071225]
                        ]
                    ])
                })
            ]
        }),
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: "#ff5722d6"
            }),
            stroke: new ol.style.Stroke({
                color: "#ffb800"
            })
        })
    })
    map.addLayer(triangle)
    map.addLayer(rectangle)

    // 获取图层列表
    const layers = map.getLayers().getArray()
    const formEle = document.querySelector(".layer-form")
    layers.forEach(layer => {
        const props = layer.getProperties()

        console.log("props:", props)
        const layerTitle = `<label class="layui-form-label">
            ${props.title}
            <i class="layui-icon layui-icon-set-fill layui-icon-custome" data-title="${props.title}" onclick="setLayerProp(event)"></i>
            </label>`
        formEle.innerHTML += layerTitle
    });

    // 查询图层属性面板
    const layerPropEle = document.querySelector(".layer-prop-set")
    function setLayerProp(event) {
        layerPropEle.style.display = "block"
        // 解构title属性
        const { title } = event.target.dataset
        const propEle = `
            <h3>${title}</h3>
            <div class='layer-prop-item'>
                <label class="layui-label">透明度:</label>
                <div class="layer-slider-item" id="transparent-prop"></div>
            </div>`
        layerPropEle.innerHTML = propEle

        // 查找目标图层
        const targetLayer = layers.find(layer => layer.getProperties().title === title)
        layui.use(function () {
            const slider = layui.slider;
            // 渲染
            slider.render({
                elem: '#transparent-prop',
                step: 0.1, // 步长
                min: 0,
                max: 1,
                value: targetLayer.getOpacity(),
                change: function (value) {
                    console.log(value) // 滑块当前值
                    targetLayer.setOpacity(value)
                }
            })
        });
    }
</script>

OpenLayers示例数据下载,请回复关键字:ol数据

全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试

【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !


网站公告

今日签到

点亮在社区的每一天
去签到