OpenLayers 地图事件选择要素

95 阅读6分钟

前言

在GIS开发中,地图事件与要素选择是构建交互式地图应用的核心功能之一。通过监听地图事件,用户可以与地图进行动态交互,如点击、拖拽等操作。而要素选择则允许用户在地图上选取特定的地理要素,进一步进行编辑、分析或展示。本文将简要介绍如何在OpenLayers中实现地图事件的监听与要素选择,帮助开发者快速掌握这些关键功能,提升地图应用的交互性与实用性。

本文来源于OpenLayers官方例子,详情可参考官网:[https://openlayers.org/en/v9.2.4/examples/select-features.html](https://openlayers.org/en/v9.2.4/examples/select-features.html)

1. 地图交互控件(Select)

Select类属于地图交互控件之一,可以在OpenLayers开发中用于选择地图要素(矢量图层)。它的主要作用是允许用户通过点击或框选等方式,选择地图上的一个或多个要素(Feature),并对这些要素进行操作或处理。以下来源于百度翻译:

选择矢量特征的交互。默认情况下,所选特征的样式不同,因此此交互可用于视觉突出显示,以及为其他操作(如修改或输出)选择特征。有三种方法可以控制选择哪些功能:使用由条件定义的浏览器事件,以及可选的切换、添加/删除和多选项;层过滤器;以及使用过滤器选项的另一个特征过滤器。

2. 创建交互事件

创建交互样式用于在选中地图要素时高亮要素。

// 选择要素样式
const selectStyle new ol.style.Style({
    fillnew ol.style.Fill({
        color"#ffcc009e"
    }),
    strokenew ol.style.Stroke({
        color"#00ffcc",
        width2.5
    })
})

在Select交互控件中通过condition参数控制交互事件类型。
以下是OpenLayers中的交互事件对象和交互事件类型。在ol.events.condition中包括click、singleClick、pointerMove等事件类型。Select交互控件默认事件类型是singleClick。值得注意的是click事件相比singleClick事件速度要稍慢,因为click事件对于系统来说需要判断是单击还是双击事件
在如下代码中创建了点击事件、鼠标移动事件、单击事件和键盘组合事件。

// 点击事件
const clickSelect new ol.interaction.Select({
    condition: ol.events.condition.click,
    style: selectStyle
})
// 单击事件
const singleClickSelect new ol.interaction.Select({
    condition: ol.events.condition.singleClick,
    style: selectStyle
})
// 鼠标移动事件
const hoverSelect new ol.interaction.Select({
    condition: ol.events.condition.pointerMove,
    style: selectStyle
})
// 键盘事件
const keySelect new ol.interaction.Select({
    condition: function (mapBrowserEvent) {
        return ol.events.condition.click(mapBrowserEvent) && ol.events.condition.altKeyOnly(mapBrowserEvent);
    },
    style: selectStyle
})

3. 监听交互事件

通过事件委托机制处理交互事件类型,先获取到点击按钮父元素,根据event.target.dataset.type值判断点击事件类型。

在每次点击事件改变时,判断selectInteraction !== null条件,也就是先移除之前存在的交互控件。然后在switch函数中根据条件改变selectInteraction变量值,并将交互控件添加到地图中,高亮点击按钮。如果点击类型未"none"值,则移除交互控件并移除按钮高亮。

const selectElement = document.querySelector(".select-ul")
// select 监听事件
const selectChange = function (event) {
    if (selectInteraction !== null) {
        map.removeInteraction(selectInteraction)
    }
    const clickType = event.target.dataset.type
    switch (clickType) {
        case "click":
            selectInteraction = clickSelect
            break
        case "single-click":
            selectInteraction = singleClickSelect
            break
        case "hover":
            selectInteraction = hoverSelect
            break
        case "key":
            selectInteraction = keySelect
            break
        case "none":
            if (selectInteraction) {
                map.removeInteraction(selectInteraction)
            }
            selectInteraction = null
            removeAllActiveClass(".select-ul""active")
            break
    }
    if (selectInteraction !== null) {
        map.addInteraction(selectInteraction)
    }

    // 高亮按钮显示
    const targetEle = event.target
    if (clickType !== "none") {
        toogleAciveClass(targetEle, ".select-ul")
    }
}
// 事件委托
selectElement.addEventListener("click", selectChange)

4. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>OpenLayers 选择要素</title>
    <meta charset="utf-8" />

    <link rel="stylesheet" href="../../libs/css/ol9.2.4.css">

    <script src="../../js/config.js"></script>
    <script src="../../js/util.js"></script>
    <script src="../../libs/js/ol9.2.4.js"></script>
    <style>
        * {
            padding0;
            margin0;
            font-size14px;
            font-family'微软雅黑';
        }

        html,
        body {
            width100%;
            height100%;
        }

        #map {
            position: absolute;
            top50px;
            bottom0;
            width100%;
        }

        #top-content {
            position: absolute;
            width100%;
            height50px;
            line-height50px;
            backgroundlinear-gradient(135deg#ff00cc#ffcc00#00ffcc#ff0066);
            color#fff;
            text-align: center;
            font-size32px;
        }

        #top-content span {
            font-size32px;
        }

        .select-type {
            position: absolute;
            padding5px;
            top60px;
            left100px;
            background-color#ffcc00ad;
            border-radius2.5px;
        }

        .select-ul {
            list-style-type: none;
        }

        .select::after {
            display: block;
            clear: both;
            content"";
        }

        .select-li {
            float: left;
            padding5px;
            margin0 5px;
            min-width50px;
            background-color: azure;
            /* background: #cae4cf82; */
            background#cae4cfdb;
            transition: background-color 10s ease-in-out 10s;
            text-align: center;
            border-radius2.5px;
        }

        .select-li:hover {
            cursor: pointer;
            color#fff;
            filterbrightness(120%);
            backgroundlinear-gradient(135deg#c850c0#4158d0);
        }

        .active {
            backgroundlinear-gradient(135deg#c850c0#4158d0);
        }
    </style>
</head>

<body>
    <div id="top-content">
        <span>OpenLayers 选择要素</span>
    </div>
    <div id="map" title=""></div>
    <div class="select-type">
        <ul class="select-ul">
            <li class="select-li" data-type="click">点选(Click)</li>
            <li class="select-li" data-type="single-click">点选(Single Click)</li>
            <li class="select-li" data-type="hover">浮选(Hover)</li>
            <li class="select-li" data-type="key">键选(Alt+Click)</li>
            <li class="select-li" data-type="none">清除</li>
        </ul>
    </div>
</body>

</html>

<script>
    //地图投影坐标系
    const projection = ol.proj.get('EPSG:3857');
    //==============================================================================//
    //============================天地图服务参数简单介绍==============================//
    //================================vec:矢量图层==================================//
    //================================img:影像图层==================================//
    //================================cva:注记图层==================================//
    //======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================//
    //==============================================================================//
    const TDTImgLayer = new ol.layer.Tile({
        title"天地图影像图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图影像描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const TDTImgCvaLayer = new ol.layer.Tile({
        title"天地图影像注记图层",
        sourcenew ol.source.XYZ({
            url"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,
            attibutions"天地图注记描述",
            crossOrigin"anoymous",
            wrapXfalse
        })
    })
    const map = new ol.Map({
        target"map",
        loadTilesWhileInteractingtrue,
        viewnew ol.View({
            center: [102.84586425.421639],
            zoom8,
            worldsWrapfalse,
            minZoom1,
            maxZoom20,
            projection'EPSG:4326',
        }),
        layers: [TDTImgLayer],
        // 地图默认控件
        controls: ol.control.defaults.defaults({
            zoomfalse,
            attributionfalse,
            rotatefalse
        })
    })

    // 文字样式
    const labelStyle = new ol.style.Style({
        textnew ol.style.Text({
            font'12px Calibri,sans-serif',
            overflowtrue,
            // 填充色
            fillnew ol.style.Fill({
                color"#FAFAD2"
            }),
            // 描边色
            strokenew ol.style.Stroke({
                color"#2F4F4F",
                width3,
            }),
        })
    })
    // 行政区样式
    const regionStyle = new ol.style.Style({
        fillnew ol.style.Fill({
            color: [2302302500.25],
        }),
        strokenew ol.style.Stroke({
            color"#00FFFF",
            width1.25,
        }),
    })

    const style = [labelStyle, regionStyle]
    const JSON_URL = "https://geo.datav.aliyun.com/areas_v3/bound/530000_full.json"

    const layer = new ol.layer.Vector({
        sourcenew ol.source.Vector({
            urlJSON_URL,
            formatnew ol.format.GeoJSON(),
        }),
        stylefunction (feature) {
            const label = feature.get("name").split(" ").join("n")
            labelStyle.getText().setText(label)
            return style
        },
        decluttertrue
    })
    map.addLayer(layer)
    map.getView().setCenter([101.48510625.008643])
    map.getView().setZoom(6.5)

    // 选择交互事件
    let selectInteraction = null
    // 选择要素样式
    const selectStyle = new ol.style.Style({
        fillnew ol.style.Fill({
            color"#ffcc009e"
        }),
        strokenew ol.style.Stroke({
            color"#00ffcc",
            width2.5
        })
    })
    // 点击事件
    const clickSelect = new ol.interaction.Select({
        condition: ol.events.condition.click,
        style: selectStyle
    })
    // 单击事件
    const singleClickSelect = new ol.interaction.Select({
        condition: ol.events.condition.singleClick,
        style: selectStyle
    })
    // 鼠标移动事件
    const hoverSelect = new ol.interaction.Select({
        condition: ol.events.condition.pointerMove,
        style: selectStyle
    })
    // 键盘事件
    const keySelect = new ol.interaction.Select({
        conditionfunction (mapBrowserEvent) {
            return ol.events.condition.click(mapBrowserEvent) && ol.events.condition.altKeyOnly(mapBrowserEvent);
        },
        style: selectStyle
    })

    const selectElement = document.querySelector(".select-ul")
    // select 监听事件
    const selectChange = function (event) {
        if (selectInteraction !== null) {
            map.removeInteraction(selectInteraction)
        }
        const clickType = event.target.dataset.type
        switch (clickType) {
            case "click":
                selectInteraction = clickSelect
                break
            case "single-click":
                selectInteraction = singleClickSelect
                break
            case "hover":
                selectInteraction = hoverSelect
                break
            case "key":
                selectInteraction = keySelect
                break
            case "none":
                if (selectInteraction) {
                    map.removeInteraction(selectInteraction)
                }
                selectInteraction = null
                removeAllActiveClass(".select-ul""active")
                break
        }
        if (selectInteraction !== null) {
            map.addInteraction(selectInteraction)
        }
        // 点击按钮高亮
        const targetEle = event.target
        if (clickType !== "none") {
            toogleAciveClass(targetEle, ".select-ul")
        }

    }
    // 事件委托
    selectElement.addEventListener("click", selectChange)
</script>

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

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

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

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

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

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