OpenLayers 几何查询之点选

关注我,带你一起学GIS ^

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

前言

WebGIS开发中数据查询主要分为两类:属性查询和几何查询。其中几何查询方式有很多,包括点选、框选或者多边形选择,查询原理都是通过判断几何图形与查询要素之间的拓扑关系。

本节主要介绍点选查询。

1. 点选查询

在使用OpenLayers做点选查询时就不得不说一下forEachFeatureAtPixel方法了,此方法作为Map对象的属性,在做数据查询时非常简单和方便。

该方法的原理为检测视口上与像素相交的特征(要素),并对每个相交的特征(要素)执行回调。检测中包含的层可以通过选项中的layerFilter选项进行配置。forEachFeatureAtPixel具有三个参数,第一个参数为视口像素坐标;第二个参数为查询回调函数,该回调函数具有两个参数,第一个参数为查询像素处的特征要素或者渲染要素,第二个参数为查询特征要素所在的图层,若无管理图层,则该参数为空。回调函数可以返回一个真值来停止检测;第三个参数是一个可选对象,该对象包含图层过滤器属性、容差属性以及一个是否包裹世界范围的布尔参数。该方法参数描述见下表。

forEachFeatureAtPixel(pixel,callback,options)

名称

类型

描述

pixel

Pixel

像素坐标

callback

function

(feature,layer)=>{}

查询要素回调函数

options

Object

{

layerFilter:undefined|function,

hitTolerance:number,默认0

checkWrapped:boolean,默认true

}

可选对象参数,可以设置图层过滤器和查询容差值。

2. 监听地图点击事件

监听地图click事件,在回调函数中查询点击位置要素,在查询到要素时改变查询特征对象边框颜色,并弹出提示框,若未查询到特征对象,则恢复要素样式并弹出信息提示。

map.on('click', evt => {
    let isDetect = false
    let targetFeature = undefined
    const queryFeature = map.forEachFeatureAtPixel(evt.pixel, (feature, layer) => {
        isDetect = true
        targetFeature = feature
    }, {
        hitTolerance: hitDistance
    })
    if (!isDetect) {
        style.getStroke().setColor('yellow');
        const content = '<div style="padding: 10px;">未查询到要素!</div>'
        openInfoFrame(content)
    } else {
        style.getStroke().setColor('red');
        const properties = targetFeature.getProperties()
        const content = `<div style="padding: 10px;">查询到要素:${properties.name}</div>`
        openInfoFrame(content)
    }
    // 更新要素样式
    lineFeatures[0].changed()
    polygonFeatures[0].changed()
})

3. 查询容差

地图容差值默认为0,通过事件委托机制更改地图容差值并且切换点击按钮样式类。在传递非默认容差值后,在地图上点选查询图形的话可以看到在图形范围外一定距离内便可查询到要素。

// 事件委托
let hitDistance = 0
const targetEle = document.querySelector(".query-wrap")
targetEle.addEventListener('click', evt => {
    const targetEle = evt.target
    hitDistance = parseInt(targetEle.dataset.hitdistance, 10)
    toogleAciveClass(targetEle, ".query-wrap")
})

容差值为10px时。

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">
    <link rel="stylesheet" href="../../libs/layui/css/layui.css">

    <script src="../../js/config.js"></script>
    <script src="../../js/util.js"></script>
    <script src="../../libs/js/ol9.2.4.js"></script>
    <script src="../../libs/layui/layui.js"></script>
    <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;
        }

        .query-wrap {
            position: absolute;
            padding: 5px;
            top: 60px;
            left: 100px;
            background-color: #ffcc00ad;
            border-radius: 2.5px;
        }

        .query-wrap::after {
            display: block;
            clear: both;
            content: "";
        }

        .query-span {
            float: left;
            padding: 5px;
            margin: 0 5px;
            min-width: 50px;
            background-color: azure;
            background: #cae4cf82;
            transition: background-color 10s ease-in-out 10s;
            text-align: center;
            border-radius: 2.5px;
        }

        .query-span:hover {
            cursor: pointer;
            color: #fff;
            filter: brightness(120%);
            background: linear-gradient(135deg, #c850c0, #4158d0);
        }

        .query-label {
            float: left;
            padding: 5px;
            margin: 0 5px;
            min-width: 50px;
            background-color: azure;
            background: #cae4cf82;
            transition: background-color 10s ease-in-out 10s;
            text-align: center;
            border-radius: 2.5px;
        }

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

<body>
    <div id="top-content">
        <span>OpenLayers 几何查询</span>
    </div>
    <div id="map" title=""></div>
    <div class="query-wrap">
        <label class="query-label">容差距离:</label>
        <span class="query-span" data-hitDistance="0">0px</span>
        <span class="query-span" data-hitDistance="5">5px</span>
        <span class="query-span" data-hitDistance="10">10px</span>
    </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=" + TDTTOKEN,
            attibutions: "天地图影像描述",
            crossOrigin: "anoymous",
            wrapX: false
        })
    })
    const TDTImgCvaLayer = 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=" + TDTTOKEN,
            attibutions: "天地图注记描述",
            crossOrigin: "anoymous",
            wrapX: false
        })
    })
    const map = new ol.Map({
        target: "map",
        loadTilesWhileInteracting: true,
        view: new ol.View({
            center: [102.845864, 25.421639],
            zoom: 5,
            worldsWrap: false,
            minZoom: 1,
            maxZoom: 20,
            projection: 'EPSG:4326',
        }),
        layers: [TDTImgLayer]
    })

    const style = new ol.style.Style({
        fill: new ol.style.Fill({
            color: "#9b65ff30"
        }),
        stroke: new ol.style.Stroke({
            color: "yellow",
            width: 2.5,
        }),
        image: new ol.style.Circle({
            fill: new ol.style.Fill({
                color: "blue"
            }),
            radius: 2.5,
            stroke: new ol.style.Stroke({
                color: "blue",
                width: 1.5,
            }),
        })
    })
    // 添加线
    const lineJSON = {
        "type""Feature",
        "geometry": {
            "type""LineString",
            "coordinates": [
                [98.24039578644181, 25.89624850911045],
                [112.97086507288361, 26.388435875]
            ]
        },
        "properties": {
            "name""我是一条线"
        }
    }
    const lineFeatures = new ol.format.GeoJSON().readFeatures(lineJSON)
    const lineSource = new ol.source.Vector({
        features: lineFeatures,
        wrapX: false
    })
    const lineLayer = new ol.layer.Vector({
        source: lineSource,
        style
    })
    map.addLayer(lineLayer)

    // 添加多边形
    const polygonJSON = {
        "type""Feature",
        "geometry": {
            "type""Polygon",
            "coordinates": [
                [
                    [87.55289525, 29.200935875],
                    [97.32633382288361, 29.552498375],
                    [97.7833634635582, 19.919685338558196],
                    [86.84977025, 19.392341588558196],
                    [87.55289525, 29.200935875]
                ]
            ]
        },
        "properties": {
            "name""我是一个面"
        }
    }
    const polygonFeatures = new ol.format.GeoJSON().readFeatures(polygonJSON)
    const polygonSource = new ol.source.Vector({
        features: polygonFeatures,
        wrapX: false
    })
    const polygonLayer = new ol.layer.Vector({
        source: polygonSource,
        style
    })
    map.addLayer(polygonLayer)

    // 事件委托
    let hitDistance = 0
    const targetEle = document.querySelector(".query-wrap")
    targetEle.addEventListener('click', evt => {
        const targetEle = evt.target
        hitDistance = parseInt(targetEle.dataset.hitdistance, 10)
        toogleAciveClass(targetEle, ".query-wrap")
    })

    map.on('click', evt => {
        let isDetect = false
        let targetFeature = undefined
        const queryFeature = map.forEachFeatureAtPixel(evt.pixel, (feature, layer) => {
            isDetect = true
            targetFeature = feature
        }, {
            hitTolerance: hitDistance
        })
        if (!isDetect) {
            style.getStroke().setColor('yellow');
            const content = '<div style="padding: 10px;">未查询到要素!</div>'
            openInfoFrame(content)
        } else {
            style.getStroke().setColor('red');

            const properties = targetFeature.getProperties()
            const content = `<div style="padding: 10px;">查询到要素:${properties.name}</div>`
            openInfoFrame(content)
        }
        lineFeatures[0].changed()
        polygonFeatures[0].changed()
    })

    /**
     * layui弹出层
     */
    function openInfoFrame(content) {
        layui.use(function () {
            var layer = layui.layer;
            // 在此处输入 layer 的任意代码
            layer.open({
                type: 1, // page 层类型
                area: ['500px''100px'],
                title: '查询要素',
                shade: 0, // 遮罩透明度
                shadeClose: true, // 点击遮罩区域,关闭弹层
                maxmin: true, // 允许全屏最小化
                anim: 0, // 0-6 的动画形式,-1 不开启
                content: content
            });
        })
    }

</script>

OpenLayers示例数据下载,请在公众号后台回复:ol数据

全国信息化工程师-GIS 应用水平考试资料,请在公众号后台回复:GIS考试

GIS之路公众号已经接入了智能助手,欢迎大家前来提问。

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

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

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

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部