Cesium 加载 Geoserver 图层以及范围过滤

2023-12-18 15:35:25

Cesium 加载 Geoserver 图层以及范围过滤

Cesium 加载 Geoserver 图层,除了会遇到属性条件查询需求,还经常遇到空间查询,这里介绍一下范围查询。

其实就是利用 Geoserver 的 CQL_FILTER 实现功能,即增加 BOX(EXTENT )条件。

本文包括范围过滤核心代码、完整代码以及在线示例。


范围过滤核心代码

Geoserver 范围过滤核心代码:


const parameters = {
    transparent: true,
    format: "image/png",
    srs: "EPSG:4326",
    // 非必填
    styles: style || "",
}

// geoserver 传入范围
bbox && (parameters.cql_filter = ' bbox(the_geom,' + bbox + ')');

// 添加geoserver发布的wms数据
layer = viewer.imageryLayers.addImageryProvider(new Cesium.WebMapServiceImageryProvider({
    url: "http://openlayers.vip/geoserver/cite/wms",
    // 必填
    layers: "cite:2000",
    parameters: parameters
}));


完整代码:


<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Use correct character set. -->
    <meta charset="utf-8"/>
    <!-- Tell IE to use the latest, best version. -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
    <meta
            name="viewport"
            content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <title>Cesium WMS EXTENT</title>
    <script src="./Cesium.js"></script>
    <script src="http://www.openlayers.vip/examples/resources/jquery-3.5.1.min.js"></script>
    <style>
        @import url(./Widgets/widgets.css);

        html,
        body,
        #cesiumContainer {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
    </style>
    <script>
        var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?f80a36f14f8a73bb0f82e0fdbcee3058";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>
</head>
<body>
<br/>
<button id="geoserverFunc" onClick="geoserverFunc()">geoserver</button>
<button id="clearFunc" onClick="clearFunc(),viewer.entities.removeAll();">清空</button>
<div id="cesiumContainer"></div>
<script>
    // 这个 tk 只能在本域名下使用
    var token = '2b7cbf61123cbe4e9ec6267a87e7442f';
    // 服务域名
    var tdtUrl = 'https://t{s}.tianditu.gov.cn/';
    // 服务负载子域
    var subdomains = ['0', '1', '2', '3', '4', '5', '6', '7'];
    var viewer = new Cesium.Viewer('cesiumContainer', {
        shouldAnimate: true,
        selectionIndicator: true,
        animation: false,       //动画
        homeButton: false,       //home键
        geocoder: false,         //地址编码
        baseLayerPicker: false, //图层选择控件
        timeline: false,        //时间轴
        fullscreenButton: false, //全屏显示
        infoBox: false,         //点击要素之后浮窗
        sceneModePicker: false,  //投影方式  三维/二维
        navigationInstructionsInitiallyVisible: false, //导航指令
        navigationHelpButton: false,     //帮助信息
        selectionIndicator: false, // 选择
        imageryProvider: new window.Cesium.WebMapTileServiceImageryProvider({
            //影像底图
            url: "http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" + token,
            subdomains: subdomains,
            layer: "tdtImgLayer",
            style: "default",
            format: "image/jpeg",
            tileMatrixSetID: "GoogleMapsCompatible",//使用谷歌的瓦片切片方式
            show: true
        })
    });

    viewer.imageryLayers.addImageryProvider(new window.Cesium.WebMapTileServiceImageryProvider({
        //影像注记
        url: "http://t{s}.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=" + token,
        subdomains: subdomains,
        layer: "tdtCiaLayer",
        style: "default",
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible",
        show: true
    }));

    // // 叠加国界服务
    var iboMap = new window.Cesium.UrlTemplateImageryProvider({
        url: tdtUrl + 'DataServer?T=ibo_w&x={x}&y={y}&l={z}&tk=' + token,
        subdomains: subdomains,
        tilingScheme: new window.Cesium.WebMercatorTilingScheme(),
        maximumLevel: 10
    });

    viewer.imageryLayers.addImageryProvider(iboMap);

    // 加载 geoserver 图层
    let layer;

    // 添加图层
    function geoserverFunc(bbox, style) {

        clearFunc();

        const parameters = {
            transparent: true,
            format: "image/png",
            srs: "EPSG:4326",
            // 非必填
            styles: style || "",
        }

        // geoserver 传入范围
        bbox && (parameters.cql_filter = ' bbox(the_geom,' + bbox + ')');

        // 添加geoserver发布的wms数据
        layer = viewer.imageryLayers.addImageryProvider(new Cesium.WebMapServiceImageryProvider({
            url: "http://openlayers.vip/geoserver/cite/wms",
            // 必填
            layers: "cite:2000",
            parameters: parameters
        }));

        flyToRectangle();
    }

    // 清空
    function clearFunc() {
        layer && viewer.imageryLayers.remove(layer) , layer = undefined;
        // viewer._container.style.cursor = "default";
    }

    /**
     * @description: 飞行定位到一个矩形
     * @return {*}
     */
    function flyToRectangle(RectangleCD) {

        // 添加定位信息
        RectangleCD = RectangleCD || [
            Cesium.Cartesian3.fromDegrees(
                115.41380999600005,
                39.44197808500007,
                0
            ),
            Cesium.Cartesian3.fromDegrees(
                117.49920000500002,
                41.05928408300005,
                0
            ),
        ];

        var rec = Cesium.Rectangle.fromCartesianArray(RectangleCD);
        var boundingSphere = Cesium.BoundingSphere.fromRectangle3D(rec);
        viewer.camera.flyToBoundingSphere(boundingSphere, {
            duration: 2,
            complete: function () {
            },
            offset: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-90),
                range: 0.0,
            },
        });
    }

    let _positions = [], floatingPoint, _entities_rectangle = [], _rectangle;

    // 标绘完加载矩形
    function loadRectangle(data) {
        var shape = viewer.entities.add({
            name: "rectangle",
            rectangle: {
                coordinates: Cesium.Rectangle.fromCartesianArray(data),
                material: Cesium.Color.RED.withAlpha(0.5)
            }
        });
        _entities_rectangle.push(shape);
        return shape;
    }

    // 创建标绘矩形
    function createRectangle() {
        var shape = viewer.entities.add({
            name: "rectangle",
            rectangle: {
                coordinates: new Cesium.CallbackProperty(function () {
                    var obj = Cesium.Rectangle.fromCartesianArray(_positions);
                    return obj;
                }, false),
                material: Cesium.Color.RED.withAlpha(0.5)
            }
        });
        _entities_rectangle.push(shape);
        return shape;
    }

    // 屏幕坐标转为弧度坐标
    function getCatesian3FromPX(px) {
        let cartesian;
        let ray = viewer.camera.getPickRay(px);
        if (!ray) return null;
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        return cartesian;
    }

    let _entities_point = [];

    // 清除锚点
    function clearPoint() {
        for (let i = 0; i < _entities_point.length; i++) {
            viewer.entities.remove(_entities_point[i]);
        }
        _entities_point = [];  //脏数据
    }

    //创建点
    function createPoint(cartesian) {
        var point = viewer.entities.add({
            position: cartesian,
            point: {
                pixelSize: 10,
                color: Cesium.Color.YELLOW,
            }
        });
        _entities_point.push(point);
        return point;
    }

    // 是否关闭已标绘矩形
    let flagDraw = false;

    // 开始标绘
    function startCreate() {

        // 关闭左键双击
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        // 鼠标形状
        viewer._container.style.cursor = "crosshair";

        let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

        // 左键单击开始绘制
        handler.setInputAction(function (evt) {
            if (flagDraw) {
                viewer.entities.removeAll();
                flagDraw = false;
            }
            //屏幕坐标转地形上坐标
            let cartesian = getCatesian3FromPX(evt.position);
            if (_positions.length == 0) {
                _positions.push(cartesian.clone());
                floatingPoint = createPoint(cartesian);
                createPoint(cartesian);// 绘制点
            }
            _positions.push(cartesian);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        // 移动绘制矩形
        handler.setInputAction(function (evt) {
            if (_positions.length < 3) return;
            let cartesian = getCatesian3FromPX(evt.endPosition);
            if (!Cesium.defined(_rectangle)) {
                _rectangle = createRectangle();
            }
            floatingPoint.position.setValue(cartesian);
            if (_rectangle) {
                _positions.pop();
                _positions.push(cartesian);
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        // 右键单击结束绘制
        handler.setInputAction(function (evt) {
            if (!_rectangle) return;
            let cartesian = getCatesian3FromPX(evt.position);
            _positions.pop();
            _positions.push(cartesian);
            createPoint(cartesian);// 绘制点
            _rectangleData = _positions.concat();
            viewer.entities.remove(_rectangle); //移除
            _rectangle = null;
            _positions = [];
            floatingPoint.position.setValue(cartesian);
            let rectangle = loadRectangle(_rectangleData); //加载

            let southwest = Cesium.Rectangle.southwest(rectangle.rectangle.coordinates._value);
            let northeast = Cesium.Rectangle.northeast(rectangle.rectangle.coordinates._value);

            // 转换为 bbox 字符
            let tempResult = Cesium.Math.toDegrees(southwest.longitude) + ',';
            tempResult += Cesium.Math.toDegrees(southwest.latitude) + ',';
            tempResult += Cesium.Math.toDegrees(northeast.longitude) + ',';
            tempResult += Cesium.Math.toDegrees(northeast.latitude);

            _entities_rectangle.push(rectangle);

            // _rectangleLast = rectangle;

            geoserverFunc(tempResult);

            flagDraw = true;

        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

        alert('一次单击两次,并且拖动画矩形和修改矩形,右击结束并保存 BBOX!');
    }

    geoserverFunc()
    startCreate()
</script>
</body>
</html>



在线示例

在这里插入图片描述

Cesium 在线示例:Cesium 图层以及范围过滤

文章来源:https://blog.csdn.net/linzi19900517/article/details/134897713
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。