OpenLayers 几何查询之点选

72 阅读2分钟

前言

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

本节主要介绍点选查询。

1. 点选查询

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

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

forEachFeatureAtPixel(pixel,callback,options)
名称类型描述
pixelPixel像素坐标
callbackfunction(feature,layer)=>{}查询要素回调函数
optionsObject{layerFilter:undefinedfunction,hitTolerance:number,默认0checkWrapped: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>
        * {
            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;
        }

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

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

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

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

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

        .active {
            backgroundlinear-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"天地图影像图层",
        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],
            zoom5,
            worldsWrapfalse,
            minZoom1,
            maxZoom20,
            projection'EPSG:4326',
        }),
        layers: [TDTImgLayer]
    })

    const style = new ol.style.Style({
        fillnew ol.style.Fill({
            color"#9b65ff30"
        }),
        strokenew ol.style.Stroke({
            color"yellow",
            width2.5,
        }),
        imagenew ol.style.Circle({
            fillnew ol.style.Fill({
                color"blue"
            }),
            radius2.5,
            strokenew ol.style.Stroke({
                color"blue",
                width1.5,
            }),
        })
    })
    // 添加线
    const lineJSON = {
        "type""Feature",
        "geometry": {
            "type""LineString",
            "coordinates": [
                [98.2403957864418125.89624850911045],
                [112.9708650728836126.388435875]
            ]
        },
        "properties": {
            "name""我是一条线"
        }
    }
    const lineFeatures = new ol.format.GeoJSON().readFeatures(lineJSON)
    const lineSource = new ol.source.Vector({
        features: lineFeatures,
        wrapXfalse
    })
    const lineLayer = new ol.layer.Vector({
        source: lineSource,
        style
    })
    map.addLayer(lineLayer)

    // 添加多边形
    const polygonJSON = {
        "type""Feature",
        "geometry": {
            "type""Polygon",
            "coordinates": [
                [
                    [87.5528952529.200935875],
                    [97.3263338228836129.552498375],
                    [97.783363463558219.919685338558196],
                    [86.8497702519.392341588558196],
                    [87.5528952529.200935875]
                ]
            ]
        },
        "properties": {
            "name""我是一个面"
        }
    }
    const polygonFeatures = new ol.format.GeoJSON().readFeatures(polygonJSON)
    const polygonSource = new ol.source.Vector({
        features: polygonFeatures,
        wrapXfalse
    })
    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.hitdistance10)
        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({
                type1// page 层类型
                area: ['500px''100px'],
                title'查询要素',
                shade0// 遮罩透明度
                shadeClosetrue// 点击遮罩区域,关闭弹层
                maxmintrue// 允许全屏最小化
                anim0// 0-6 的动画形式,-1 不开启
                content: content
            });
        })
    }

</script>

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

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

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

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

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

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