# cesium-ol二三维联动(鹰眼图)

cesium除了使用两个viewer联动的方式实现鹰眼图,还有其他方式

这里我使用cesium和ol联动的方式实现鹰眼图(也可以实现简单的二三维联动效果)

# 实现思路

  1. 监听cesium地图的移动
  2. 当移动视图时,计算cesium视图范围,并传递给ol
  3. 监听ol地图移动,当ol移动时,计算ol的视图范围
  4. 传递给cesium(cesium会垂直移动)

# 实现代码

<!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>二三维联动</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/openlayers/4.6.5/ol.css" rel="stylesheet">
    <script src="../Cesium-1.89/Build/Cesium/Cesium.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/openlayers/4.6.5/ol.js"></script>
    <script  src="Cesium2DLink3DUtil.js"></script>
    <style>
        @import url(../Cesium-1.89/Build/Cesium/Widgets/widgets.css);
        html,
        body,
        .main-view,
        #cesiumContainer {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        .toolbox {
            position: absolute;
            top: 49%;
            left: 30px;
            z-index: 99;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
        }
        .tool-item {
            background-color: #303336;
            cursor: pointer;
        }


        #eye {
            position: absolute;
            width: 20%;
            height: 20%;
            bottom: 0;
            right: 0;
            z-index: 999;
            border: solid blue 1px;
        }
    </style>
</head>
<body>

<div class="main-view" style="position: relative;display: flex">
    <div class="toolbox">
        <button id='point' style="color: white;" class="tool-item">联动</button>
        <button id='clear' style="color: white;" class="tool-item">关闭</button>
    </div>
    <div id="cesiumContainer"></div>
</div>
</body>
<script type="module">


    let viewer = new Cesium.Viewer('cesiumContainer', {
        imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
            url : 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
        }),
        geocoder: false,
        homeButton: false,
        sceneModePicker: false,
        baseLayerPicker: false,
        navigationHelpButton: false,
        animation: false,
        timeline: false,
        fullscreenButton: false,
        vrButton: false,
        mapProjection: new Cesium.WebMercatorProjection(),
    });

    viewer._cesiumWidget._creditContainer.style.display = 'none'; // 隐藏版权

    var linkUtil =  new Cesium2DLinkage3DUtil()
    document.getElementById('point').onclick = function(){
        if(linkUtil.isActive)return
        linkUtil.active(viewer)
    }
    document.getElementById('clear').onclick = function(){
        linkUtil.deactive()
    }
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

# 核心js方法

/**
 * 二三维联动,二维openlayers,三维Cesium
 */

class Cesium2DLinkage3DUtil {
    constructor(mapId = 'eye') {
        this.mapId = mapId

        this.isActive = false
        this.isIn2DMapFlag = false;

        this.mouseMoveEvent = this.mouseMoveEvent.bind(this)
        this.getViewCameraRectrange = this.getViewCameraRectrange.bind(this)
        this.changeCenterListener = this.changeCenterListener.bind(this)
    }

    /**
     * 初始化地图容器,插入三维容器的左侧
     */
    init2DDiv() {
        this.mapDiv = document.createElement('div');
        this.mapDiv.setAttribute('id', this.mapId)

        // insertBefore
        const viewerContainer = this.viewer.cesiumWidget.container.parentElement.parentElement
        viewerContainer.parentNode.insertBefore(this.mapDiv, viewerContainer)
    }

    /**
     * 初始化地图视图
     */
    init2DMap() {
        //普通地图
        const tiandituVecLayer = new ol.layer.Tile({
            title: 'generalMap',
            source: new ol.source.XYZ({
                url: 'http://t3.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=token',
                crossOrigin: 'anonymous'
            }),
            visible: true
        });
        //普通地图标记
        const tiandituCvaLayer = new ol.layer.Tile({
            title: 'generalMapZj',
            source: new ol.source.XYZ({
                url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=token',
                crossOrigin: 'anonymous'
            }),
            visible: true
        });
        this.olMap = new ol.Map({
            layers: [tiandituVecLayer,tiandituCvaLayer],
            target: this.mapId,
            view: new ol.View({
                center: [13818313.960985335, 6519709.935426011],
                zoom: 8,
                projection: 'EPSG:3857',
                maxZoom: 22
            }),
            // 设置地图控件,默认的三个控件都不显示
            controls: ol.control.defaults({
                attribution: false,
                rotate: false,
                zoom: false
            }),
        });

        this.olMap.updateSize()
    }


    /**
     * 二维监听事件处理
     */
    changeCenterListener() {
        if (this.isIn2DMapFlag) {
            const bounds = this.olMap.getView().calculateExtent();
            const boundsTansform = ol.proj.transformExtent(bounds, 'EPSG:3857', 'EPSG:4326')
            this.viewer.camera.setView({
                heading : Cesium.Math.toRadians(120.0),//方向
                pitch : Cesium.Math.toRadians(-10),//倾斜角度
                roll: this.viewer.camera.roll,
                destination: Cesium.Rectangle.fromDegrees(
                    boundsTansform[0],
                    boundsTansform[1],
                    boundsTansform[2],
                    boundsTansform[3],
                )

            });
        }
    }

    /**
     * 三维监听事件处理
     */
    getViewCameraRectrange() {
        const rectangle = this.viewer.camera.computeViewRectangle();
        // 弧度转为经纬度

        const west = (rectangle.west / Math.PI) * 180;

        const north = (rectangle.north / Math.PI) * 180;

        const east = (rectangle.east / Math.PI) * 180;

        const south = (rectangle.south / Math.PI) * 180;
        //三维联动二维界面
        if (!this.isIn2DMapFlag) {
            if (north > 87 && south < -87) {
                const center = this.getCenterPosition(this.viewer);
                this.olMap.getView().setZoom(0);
                this.olMap.getView().setCenter(ol.proj.transform([center.lon, center.lat], 'EPSG:4326', 'EPSG:3857'));
            } else {
                this.olMap.getView().fit(ol.proj.transformExtent([west, south, east, north], 'EPSG:4326', 'EPSG:3857'));

            }

        }
    }

    /**
     * 判断鼠标是否在二维地图
     * @param x
     * @param y
     * @return {boolean}
     */
    isMouseIn2DMap(x, y) {
        let y1 = this.mapDiv.offsetTop; //div上面两个的点的y值
        let y2 = y1 + this.mapDiv.clientHeight; //div下面两个点的y值
        let x1 = this.mapDiv.offsetLeft; //div左边两个的点的x值
        let x2 = x1 + this.mapDiv.clientWidth; //div右边两个点的x的值
        return !(x < x1 || x > x2 || y < y1 || y > y2);
    }

    addListener() {
        this.olMap.getView().on("change:center", this.changeCenterListener);
        this.olMap.updateSize()
        this.viewer.cesiumWidget.container.parentElement.parentElement.parentElement.addEventListener('mousemove', this.mouseMoveEvent)
        this.viewer.scene.preRender.addEventListener(this.getViewCameraRectrange);
    }

    removeListener(){
        this.olMap.getView().un("change:center", this.changeCenterListener);
        this.viewer.scene.preRender.removeEventListener(this.getViewCameraRectrange)
        this.viewer.cesiumWidget.container.parentElement.parentElement.parentElement.removeEventListener('mousemove', this.mouseMoveEvent)
        this.mapDiv.style.width = '0%';
        this.mapDiv.parentNode.removeChild(this.mapDiv)
        this.olMap = null;
    }


    mouseMoveEvent(e) {
        this.isIn2DMapFlag = this.isMouseIn2DMap(e.pageX, e.pageY);
    }

    getCenterPosition(viewer) {
        const result = viewer.camera.pickEllipsoid(
            new Cesium.Cartesian2(
                viewer.canvas.clientWidth / 2,
                viewer.canvas.clientHeight / 2
            )
        );
        const curPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(result);
        const lon = (curPosition.longitude * 180) / Math.PI;
        const lat = (curPosition.latitude * 180) / Math.PI;
        return {
            lon: lon,
            lat: lat
        };
    }


    active(viewer) {
        this.viewer = viewer
        this.isActive = true
        this.init2DDiv()
        this.init2DMap()
        this.addListener()
    }

    deactive() {
        this.removeListener()
        this.isActive =  false
        this.viewer = undefined
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

# 实现效果

image-20220112204954605

上次更新时间: 2022年5月20日星期五上午11点16分