OpenLayers 矢量要素查询

79 阅读4分钟

前言

矢量要素查询作为一项核心功能,在GIS开发中具有重要作用,能够帮助用户快速定位和获取地图上特定的要素信息。在GIS系统开发中,要做到高效而精确的查询和分析地理数据是衡量地理信息系统可用性的重要指标。而在OpenLayers中可以使用多种查询方式满足可这一需求。

本文将详细介绍如何在 OpenLayers 中使用矢量图层实现矢量要素查询。

1. 创建矢量图层

在OpenLayers中创建矢量图层非常简单,使用Vector类创建矢量图层,然后添加GeoJSON等矢量数据源即可。其中background属性用于设置背景样式,style属性使用ol样式表达式,概念比较难以理解,可以先不用管😕😕。

// 行政区矢量图层
const regionLayer = new ol.layer.Vector({
    background'#41748099',
    source: new ol.source.Vector({
        url: JSON_URL,
        format: new ol.format.GeoJSON()
    }),
    style: {
        'fill-color': ['string', ['get''COLOR'], '#eee'],
    }
})
map.addLayer(regionLayer)
map.getView().setCenter([101.48510625.008643])
map.getView().setZoom(6.5)

矢量图层创建完成之后,将其添加到地图中,并更新视图中心点和视图缩放级别。

2. 要素属性查询

在GIS开发中,信息弹窗用于展示地图属性信息,有利于提升用户体验。在代码中使用矢量图层对象方法getFeatures查询地图要素,该方法接收一个事件坐标参数,然后返回一个实现了features数组的Promise对象。

getFeatures方法用于获取地图视口与事件像素相交的最顶部要素,当检测到特征要素时,features数组将包含最顶部特征,否则为空。用于此方法的命中检测算法针对性能进行了优化,但不如map.getFeaturesAtPixel()中使用的算法准确。不考虑文本,图标仅由其边界框表示,而不是精确的图像。

// 高亮要素
let highlightFeat = undefined
function showPopupInfo(pixel) {
    regionLayer.getFeatures(pixel).then(features => {
        // 若未查询到要素,则退出
        if (!features.length) {
            if (highlightFeat) {
                highlightLayer.getSource().removeFeature(highlightFeat)
                highlightFeat = undefined
            }
            return
        }
        // 获取要素属性
        const properties = features[0].getProperties()
        // 将事件坐标转换为地图坐标
        const coords = map.getCoordinateFromPixel(pixel)
        if (features[0] != highlightFeat) {
            // 移除高亮要素
            if (highlightFeat) {
                highlightLayer.getSource().removeFeature(highlightFeat)
                highlightFeat = undefined
            }
            highlightLayer.getSource().addFeature(features[0])
            highlightFeat = features[0]
        }
        openPopupTable(properties, popupColums, coords)
    })
}

如果查询到要素,则显示信息弹窗并高亮目标要素。

getCoordinateFromPixel方法用于将事件像素坐标转换为地图坐标,在打开信息弹窗方法openPopupTable中需要传递该地图坐标。openPopupTable为自定义信息弹窗方法,读者可考虑自行实现。

3. 监听鼠标事件

监听鼠标点击事件和移动事件,并在事件处理函数中调用显示信息弹窗方法。

// 监听地图鼠标移动事件
map.on("pointermove", evt => {
    // 若正在拖拽地图,则退出
    if (evt.dragging) return
    const pixel = map.getEventPixel(evt.originalEvent)
    showPopupInfo(pixel)
})

// 监听地图鼠标点击事件
map.on("click", evt => {
    // 若正在拖拽地图,则退出
    if (evt.dragging) return
    showPopupInfo(evt.pixel)
})

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="../../../css/popup.css">

    <script src="../../../js/config.js"></script>
    <script src="../../../js/util.js"></script>
    <script src="../../../js/popup.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;
        }
    </style>
</head>

<body>
    <div id="top-content">
        <span>OpenLayers 加载矢量影像图层</span>
    </div>
    <div id="map" title=""></div>
</body>

</html>

<script>
    //==============================================================================//
    //============================天地图服务参数简单介绍==============================//
    //================================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]
    })
    window._map = map

    const JSON_URL = "../../../data/geojson/yn_region.json"
    // 矢量影像图层
    const regionLayer = new ol.layer.VectorImage({
        background'#41748099',
        imageRatio2,
        sourcenew ol.source.Vector({
            urlJSON_URL,
            formatnew ol.format.GeoJSON()
        }),
        style: {
            'fill-color': ['string', ['get''COLOR'], '#eee'],
        }
    })
    map.addLayer(regionLayer)
    map.getView().setCenter([101.48510625.008643])
    map.getView().setZoom(6.5)

    // 高亮图层
    highlightLayer = new ol.layer.Vector({
        sourcenew ol.source.Vector({}),
        map: map,
        style: {
            "stroke-color"'#3CF9FF',
            "stroke-width"2.5
        }
    })

    // Popup 模板
    const popupColums = [
        {
            name"adcode",
            comment"行政区代码"
        },
        {
            name"name",
            comment"行政区名称"
        },
        {
            name"GDP",
            comment"GDP"
        },
        {
            name"unit",
            comment"单位"
        },
        {
            name"level",
            comment"级别"
        },
        {
            name"COLOR",
            comment"颜色"
        }
    ]
    // 高亮要素
    let highlightFeat = undefined
    function showPopupInfo(pixel) {
        regionLayer.getFeatures(pixel).then(features => {
            // 若未查询到要素,则退出
            if (!features.length) {
                if (highlightFeat) {
                    highlightLayer.getSource().removeFeature(highlightFeat)
                    highlightFeat = undefined
                }
                return
            }
            // 获取要素属性
            const properties = features[0].getProperties()
            // 将事件坐标转换为地图坐标
            const coords = map.getCoordinateFromPixel(pixel)
            if (features[0] != highlightFeat) {
                // 移除高亮要素
                if (highlightFeat) {
                    highlightLayer.getSource().removeFeature(highlightFeat)
                    highlightFeat = undefined
                }
                highlightLayer.getSource().addFeature(features[0])
                highlightFeat = features[0]
            }
            openPopupTable(properties, popupColums, coords)
        })
    }

    // 监听地图鼠标移动事件
    map.on("pointermove"evt => {
        // 若正在拖拽地图,则退出
        if (evt.draggingreturn
        const pixel = map.getEventPixel(evt.originalEvent)
        showPopupInfo(pixel)
    })

    // 监听地图鼠标点击事件
    map.on("click"evt => {
        // 若正在拖拽地图,则退出
        if (evt.draggingreturn
        showPopupInfo(evt.pixel)
    })
</script>