Menu

  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay
  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay

Cesium学习笔记

17
Mar
2015

Cesium学习笔记

By Alex
/ in GIS,JavaScript
/ tags WebGL
7 Comments
Cesium简介

Cesium是一个基于JavaScript的开源框架,可用于在浏览器中绘制3D的地球,并在其上绘制地图(支持多种格式的瓦片服务),该框架不需要任何插件支持,但是浏览器必须支持WebGL。

Cesium支持多种数据可视化方式,可以绘制各种几何图形、导入图片,甚至3D模型。同时,Cesium还支持基于时间轴的动态数据展示,例如,我们可以用它绘制卫星运行轨迹。

Cesium HelloWorld

下面的例子在浏览器中显示一个太空背景、具有地图覆盖的3D地球:

index.html
XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>Cesium Example</title>
<script src="Cesium-1.7.1/Build/CesiumUnminified/Cesium.js"></script>
<link rel="stylesheet" type="text/css" href="Cesium-1.7.1/Build/CesiumUnminified/Widgets/widgets.css"></link>
<style>
html,body,#cesiumContainer {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
}
</style>
</head>
<body>
    <div id="cesiumContainer"></div>
    <script type="text/javascript" src="index.js"></script>
</body>
</html>

index.js
JavaScript
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
var viewer = new Cesium.Viewer( 'cesiumContainer', {
    animation : false,//是否创建动画小器件,左下角仪表
    baseLayerPicker : false,//是否显示图层选择器
    fullscreenButton : false,//是否显示全屏按钮
    geocoder : false,//是否显示geocoder小器件,右上角查询按钮
    homeButton : false,//是否显示Home按钮
    infoBox : false,//是否显示信息框
    sceneModePicker : false,//是否显示3D/2D选择器
    selectionIndicator : false,//是否显示选取指示器组件
    timeline : false,//是否显示时间轴
    navigationHelpButton : false,//是否显示右上角的帮助按钮
    scene3DOnly : true,//如果设置为true,则所有几何图形以3D模式绘制以节约GPU资源
    clock : new Cesium.Clock(),//用于控制当前时间的时钟对象
    selectedImageryProviderViewModel : undefined,//当前图像图层的显示模型,仅baseLayerPicker设为true有意义
    imageryProviderViewModels : Cesium.createDefaultImageryProviderViewModels(),//可供BaseLayerPicker选择的图像图层ProviderViewModel数组
    selectedTerrainProviderViewModel : undefined,//当前地形图层的显示模型,仅baseLayerPicker设为true有意义
    terrainProviderViewModels : Cesium.createDefaultTerrainProviderViewModels(),//可供BaseLayerPicker选择的地形图层ProviderViewModel数组
    imageryProvider : new Cesium.OpenStreetMapImageryProvider( {
        credit :'',
        url : '//192.168.0.89:5539/planet-satellite/'
    } ),//图像图层提供者,仅baseLayerPicker设为false有意义
    terrainProvider : new Cesium.EllipsoidTerrainProvider(),//地形图层提供者,仅baseLayerPicker设为false有意义
    skyBox : new Cesium.SkyBox({
        sources : {
          positiveX : 'Cesium-1.7.1/Skybox/px.jpg',
          negativeX : 'Cesium-1.7.1/Skybox/mx.jpg',
          positiveY : 'Cesium-1.7.1/Skybox/py.jpg',
          negativeY : 'Cesium-1.7.1/Skybox/my.jpg',
          positiveZ : 'Cesium-1.7.1/Skybox/pz.jpg',
          negativeZ : 'Cesium-1.7.1/Skybox/mz.jpg'
        }
    }),//用于渲染星空的SkyBox对象
    fullscreenElement : document.body,//全屏时渲染的HTML元素,
    useDefaultRenderLoop : true,//如果需要控制渲染循环,则设为true
    targetFrameRate : undefined,//使用默认render loop时的帧率
    showRenderLoopErrors : false,//如果设为true,将在一个HTML面板中显示错误信息
    automaticallyTrackDataSourceClocks : true,//自动追踪最近添加的数据源的时钟设置
    contextOptions : undefined,//传递给Scene对象的上下文参数(scene.options)
    sceneMode : Cesium.SceneMode.SCENE3D,//初始场景模式
    mapProjection : new Cesium.WebMercatorProjection(),//地图投影体系
    dataSources : new Cesium.DataSourceCollection()
    //需要进行可视化的数据源的集合
} );
var scene = viewer.scene;
var canvas = viewer.canvas;
var clock = viewer.clock;
var camera = viewer.scene.camera;
var entities = viewer.entities;

可以加快时间的运行,并且模拟日光照射效果:

index.js
JavaScript
1
2
3
4
//加快时钟的运行
clock.multiplier = 0.1 * 60 * 60;
//阳光照射区域高亮
scene.globe.enableLighting = true;

通过以下代码,可以设置镜头位置与指向,Cesium的Camera对象提供了多种操控镜头的方法:

index.js
JavaScript
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
//设置镜头位置与方向
camera.setView( {
    //镜头的经纬度、高度。镜头默认情况下,在指定经纬高度俯视(pitch=-90)地球
    position : Cesium.Cartesian3.fromDegrees( 116.3, 39.9, 100000000 ),//北京100000公里上空
    //下面的几个方向正好反映默认值
    heading : Cesium.Math.toRadians( 0 ),
    pitch : Cesium.Math.toRadians( -90 ),
    roll : Cesium.Math.toRadians( 0 )
} );
//让镜头飞行(动画)到某个地点和方向
setTimeout( function()
{
    camera.flyTo( {
        destination : Cesium.Cartesian3.fromDegrees( 116, 15, 6000000 ),
        orientation : {
            heading : Cesium.Math.toRadians( -15 ),
            pitch : Cesium.Math.toRadians( -65 ),
            roll : Cesium.Math.toRadians( 0 )
        },
        duration : 3,//动画持续时间
        complete : function()//飞行完毕后执行的动作
        {
            addEntities();
        }
    } );
}, 1000 );
 
//监听键盘事件,用于平移或者旋转镜头
var ellipsoid = scene.globe.ellipsoid;
canvas.onclick = function()
{
    canvas.focus();
};
var flags = {
    looking : false,
    rotateLeft : false,
    rotateRight : false,
    moveUp : false,
    moveDown : false,
    moveLeft : false,
    moveRight : false
};
var handler = new Cesium.ScreenSpaceEventHandler( canvas );
function getFlagForKeyCode( keyCode )
{
    switch ( keyCode )
    {
        case 'W'.charCodeAt( 0 ) : //向下平移镜头
            return 'moveDown';
        case 'S'.charCodeAt( 0 ) : //向上平移镜头
            return 'moveUp';
        case 'A'.charCodeAt( 0 ) : //向右平移镜头
            return 'moveRight';
        case 'D'.charCodeAt( 0 ) : //向左平移镜头
            return 'moveLeft';
        case 'Q'.charCodeAt( 0 ) : //向右旋转镜头
            return 'rotateRight';
        case 'E'.charCodeAt( 0 ) : //向左旋转镜头
            return 'rotateLeft';
        default :
            return undefined;
    }
}
document.addEventListener( 'keydown', function( e )
{
    var flagName = getFlagForKeyCode( e.keyCode );
    if ( typeof flagName !== 'undefined' )
    {
        flags[flagName] = true;
    }
}, false );
document.addEventListener( 'keyup', function( e )
{
    var flagName = getFlagForKeyCode( e.keyCode );
    if ( typeof flagName !== 'undefined' )
    {
        flags[flagName] = false;
    }
}, false );
viewer.clock.onTick.addEventListener( function( clock )
{
    var cameraHeight = ellipsoid.cartesianToCartographic( camera.position ).height;
    var moveRate = cameraHeight / 100.0;
 
    if ( flags.rotateLeft )
    {
        camera.rotateLeft( 0.01 );
    }
    if ( flags.rotateRight )
    {
        camera.rotateRight( 0.01 );
    }
    if ( flags.moveUp )
    {
        camera.moveUp( moveRate );
    }
    if ( flags.moveDown )
    {
        camera.moveDown( moveRate );
    }
    if ( flags.moveLeft )
    {
        camera.moveLeft( moveRate );
    }
    if ( flags.moveRight )
    {
        camera.moveRight( moveRate );
    }
} );

可以添加若干实体,实体可以用于组织多个可视化对象,下面的例子模拟了卫星波束的覆盖范围:

index.js
JavaScript
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
/**
* 根据偏移量计算目标点经纬度
* @param {} start  起始点经纬度数组,单位度
* @param {} offset 东北方向的偏移量,单位米
* @param {} 目标点经纬度数组,单位度
*/
function offsetToLongLat( start, offset )
{
    var er = 6378137;
    var lat = parseFloat( start[1] );
    var lon = parseFloat( start[0] );
    var dn = parseFloat( offset[1] );
    var de = parseFloat( offset[0] );
 
    dLat = dn / er;
    var pi = Math.PI;
    var dLon = de / ( er * Math.cos( pi * lat / 180 ) )
    return [
        lon + dLon * 180 / pi, lat + dLat * 180 / pi
    ];
}
/**
* 通过绘制三角形模拟卫星光束效果
* @param {} entities 实体集
* @param {} stltPos 卫星三维坐标数组
* @param {} points 地面点
* @param {} color CSS颜色代码,例如#FF0000
*/
function lightShinePolygon( entities, stltPos, points, color )
{
    for ( var i = 0; i < points.length; i += 2 )
    {
        var array = [
            stltPos[0], stltPos[1], stltPos[2], points[i], points[i + 1], 0
        ];
        if ( i + 2 == points.length )
        {
            array.push( points[0] );
            array.push( points[1] );
        }
        else
        {
            array.push( points[i + 2] );
            array.push( points[i + 3] );
        }
        array.push( 0 );
        entities.add( {
            polygon : {
                hierarchy : Cesium.Cartesian3.fromDegreesArrayHeights( array ),
                perPositionHeight : true,
                outline : false,
                material : Cesium.Color.fromAlpha( Cesium.Color.fromCssColorString( color ), .1 )
            }
        } );
    }
}
/**
* 添加实体
*/
function addEntities()
{
    //卫星一
    {
        var stltPos = [
            110.0, 40.0, 2500000
        ];
        entities.add( {
            position : Cesium.Cartesian3.fromDegrees.apply( this, stltPos ),
            billboard : {
                image : 'images/satellite-1.png',
                horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
                verticalOrigin : Cesium.VerticalOrigin.BOTTOM, //垂直方向位置计算基准设为底部,默认中心
                width : 92,
                height : 36
            }
        } );
        //一个多边形覆盖范围
        {
            var color = '#FF0000';
            //模拟光照效果的若干多边形
            var points = [
                100, 48, 110, 40, 115, 40, 120, 43, 120, 55
            ];
            lightShinePolygon( entities, stltPos, points, color );
            //地面多边形
            entities.add( {
                polygon : {
                    hierarchy : Cesium.Cartesian3.fromDegreesArray( points ),
                    outline : true,
                    outlineColor : Cesium.Color.fromAlpha( Cesium.Color.fromCssColorString( color ), .4 ),
                    material : Cesium.Color.fromAlpha( Cesium.Color.fromCssColorString( color ), .3 )
                }
            } );
        }
 
        //一个圆形覆盖范围
        {
            var r = 600000;//半径
            var color = '#0000FF';
            //圆心
            var ecLong = 110.0;
            var ecLat = 30.0;
            var ec = Cesium.Cartesian3.fromDegrees( ecLong, ecLat, 0 );
            //模拟光照效果的若干多边形
            var points = [];
            for ( var i = 0; i < 360; i += 30 )
            {
                var coord = offsetToLongLat( [
                    ecLong, ecLat
                ], [
                    Math.cos( Math.PI * i / 180 ) * r, Math.sin( Math.PI * i / 180 ) * r
                ] );
                points.push( coord[0] );
                points.push( coord[1] );
            }
            lightShinePolygon( entities, stltPos, points, color );
            //圆
            viewer.entities.add( {
                position : ec,
                ellipse : {
                    semiMinorAxis : r,
                    semiMajorAxis : r,
                    height : 0.0,
                    outline : true,
                    outlineColor : Cesium.Color.fromAlpha( Cesium.Color.fromCssColorString( color ), .4 ),
                    material : Cesium.Color.fromAlpha( Cesium.Color.fromCssColorString( color ), .3 )
                }
            } );
        }
    }
}
空间数据可视化

Cesium提供Entity API来绘制空间数据,例如点、标记、标签、线、3D模型、形状、立体形状(volume)。

Entity API简介

Cesium提供两类API:

  1. 面向图形开发人员的底层API,通常称为“Primitive API”。该API暴露最小限度的抽象,使用图形学术语,具有很大的灵活性,需要具有图形学编程的知识
  2. 高级别的数据驱动的API,称为“Entity API”。该API使用一致性设计的、高级别的对象来管理一组相关性的可视化对象,其底层使用Primitive API

下面是Entity API的简单例子,用红色半透明区域标记出美国怀俄明州:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var viewer = new Cesium.Viewer('cesiumContainer'); //创建一个查看器(Viewer widget)
var wyoming = viewer.entities.add({  //添加一个实体,仅需要传递一个简单JSON对象,返回值是一个Entity对象
  name : 'Wyoming',
  polygon : {
    hierarchy : Cesium.Cartesian3.fromDegreesArray([//一组地理坐标
                              -109.080842,45.002073,
                              -105.91517,45.002073,
                              -104.058488,44.996596,
                              -104.053011,43.002989,
                              -104.053011,41.003906,
                              -105.728954,40.998429,
                              -107.919731,41.003906,
                              -109.04798,40.998429,
                              -111.047063,40.998429,
                              -111.047063,42.000709,
                              -111.047063,44.476286,
                              -111.05254,45.002073]),
    material : Cesium.Color.RED.withAlpha(0.5), //材质
    outline : true, //是否显示轮廓
    outlineColor : Cesium.Color.BLACK //轮廓的颜色
  }
});
viewer.zoomTo(wyoming);//缩放、平移视图使实体可见 
形状与立体(Shapes and Volumes)
支持的形状与立体列表
形状   代码示例
立方体
(Boxes)
JavaScript
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
var blueBox = viewer.entities.add({
    name : 'Blue box',
     //中心的位置
    position: Cesium.Cartesian3.fromDegrees(-114.0, 40.0, 300000.0),
    box : {
        //长宽高
        dimensions : new Cesium.Cartesian3(400000.0, 300000.0, 500000.0),
        material : Cesium.Color.BLUE
    }
});
 
var redBox = viewer.entities.add({
    name : 'Red box with black outline',
    position: Cesium.Cartesian3.fromDegrees(-107.0, 40.0, 300000.0),
    box : {
        dimensions : new Cesium.Cartesian3(400000.0, 300000.0, 500000.0),
        material : Cesium.Color.RED,
        outline : true, //显示轮廓
        outlineColor : Cesium.Color.BLACK
    }
});
 
var outlineOnly = viewer.entities.add({
    name : 'Yellow box outline',
    position: Cesium.Cartesian3.fromDegrees(-100.0, 40.0, 300000.0),
    box : {
        dimensions : new Cesium.Cartesian3(400000.0, 300000.0, 500000.0),
        fill : false,  //不显示填充
        outline : true,
        outlineColor : Cesium.Color.YELLOW
    }
});
圆和椭圆
(Circles Ellipses)
JavaScript
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
var viewer = new Cesium.Viewer('cesiumContainer');
//浮空的绿色圆形
var greenCircle = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(-111.0, 40.0, 150000.0),
    name : 'Green circle at height',
    ellipse : {
        semiMinorAxis : 300000.0,
        semiMajorAxis : 300000.0,
        height: 200000.0, //浮空
        material : Cesium.Color.GREEN
    }
});
//红色椭圆形,位于地表,带轮廓
var redEllipse = viewer.entities.add({
    //不带高度
    position: Cesium.Cartesian3.fromDegrees(-103.0, 40.0),
    name : 'Red ellipse on surface with outline',
    ellipse : {
        semiMinorAxis : 250000.0,
        semiMajorAxis : 400000.0,
        material : Cesium.Color.RED.withAlpha(0.5),
        outline : true,
        outlineColor : Cesium.Color.RED
    }
});
//蓝色椭圆柱,旋转了角度
var blueEllipse = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 100000.0),
    name : 'Blue translucent, rotated, and extruded ellipse',
    ellipse : {
        semiMinorAxis : 150000.0,
        semiMajorAxis : 300000.0,
        extrudedHeight : 200000.0,  //拉伸
        rotation : Cesium.Math.toRadians(45), //旋转
        material : Cesium.Color.BLUE.withAlpha(0.7),
        outline : true
    }
});
 
viewer.zoomTo(viewer.entities);
走廊
(Corridor)
JavaScript
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
var redCorridor = viewer.entities.add({
    name : 'Red corridor on surface with rounded corners and outline',
    corridor : {
        positions : Cesium.Cartesian3.fromDegreesArray([
                                                        -100.0, 40.0,
                                                        -105.0, 40.0,
                                                        -105.0, 35.0
                                                    ]),
                                                    width : 200000.0,
        material : Cesium.Color.RED.withAlpha(0.5),
        outline : true,
        outlineColor : Cesium.Color.RED
    }
});
 
var greenCorridor = viewer.entities.add({
    name : 'Green corridor at height with mitered corners',
    corridor : {
        positions : Cesium.Cartesian3.fromDegreesArray(
        [    -90.0, 40.0,
             -95.0, 40.0,
             -95.0, 35.0
        ]),
        height: 100000.0,
        width : 200000.0,
        cornerType: Cesium.CornerType.MITERED,
        material : Cesium.Color.GREEN
    }
});
 
var blueCorridor = viewer.entities.add({
    name : 'Blue extruded corridor with beveled corners and outline',
    corridor : {
        positions : Cesium.Cartesian3.fromDegreesArray(
        [    80.0, 40.0,
             -85.0, 40.0,
             -85.0, 35.0
        ]),
        height : 200000.0,
        extrudedHeight : 100000.0,
        width : 200000.0,
        cornerType: Cesium.CornerType.BEVELED,
        material : Cesium.Color.BLUE.withAlpha(0.5),
        outline : true,
        outlineColor : Cesium.Color.BLUE
    }
});
圆柱和圆锥
(Cylinder Cones)
 
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var greenCylinder = viewer.entities.add({
    name : 'Green cylinder with black outline',
    position: Cesium.Cartesian3.fromDegrees(-100.0, 40.0, 200000.0),
    cylinder : { //圆柱
        length : 400000.0,
        topRadius : 200000.0,
        bottomRadius : 200000.0,
        material : Cesium.Color.GREEN,
        outline : true,
        outlineColor : Cesium.Color.DARK_GREEN
    }
});
 
var redCone = viewer.entities.add({
    name : 'Red cone',
    position: Cesium.Cartesian3.fromDegrees(-105.0, 40.0, 200000.0),
    cylinder : {//圆锥
        length : 400000.0,
        topRadius : 0.0,
        bottomRadius : 200000.0,
        material : Cesium.Color.RED
    }
});
多边形
(Polygons)
JavaScript
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
var redPolygon = viewer.entities.add({
    name : '贴着地表的多边形',
    polygon : {
        hierarchy : Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0,
                                                        -115.0, 32.0,
                                                        -107.0, 33.0,
                                                        -102.0, 31.0,
                                                        -102.0, 35.0]),
        material : Cesium.Color.RED
    }
});
 
var greenPolygon = viewer.entities.add({
    name : '绿色拉伸多边形',
    polygon : {
        hierarchy : Cesium.Cartesian3.fromDegreesArray([-108.0, 42.0,
                                                        -100.0, 42.0,
                                                        -104.0, 40.0]),
        extrudedHeight: 500000.0,
        material : Cesium.Color.GREEN
    }
});
 
var orangePolygon = viewer.entities.add({
    name : '每个顶点具有不同拉伸高度的橘色多边形',
    polygon : {
        hierarchy : Cesium.Cartesian3.fromDegreesArrayHeights(
            [-108.0, 25.0, 100000,
             -100.0, 25.0, 100000,
             -100.0, 30.0, 100000,
             -108.0, 30.0, 300000]),
        extrudedHeight: 0,
        perPositionHeight : true,
        material : Cesium.Color.ORANGE,
        outline : true,
        outlineColor : Cesium.Color.BLACK
    }
});
 
var bluePolygon = viewer.entities.add({
    name : '具有挖空效果的蓝色多边形',
    polygon : {
        hierarchy : {
            positions : Cesium.Cartesian3.fromDegreesArray(
                [-99.0, 30.0,
                 -85.0, 30.0,
                 -85.0, 40.0,
                 -99.0, 40.0]),
            holes : [{
                positions : Cesium.Cartesian3.fromDegreesArray([
                    -97.0, 31.0,
                    -97.0, 39.0,
                    -87.0, 39.0,
                    -87.0, 31.0
                ]),
                holes : [{
                    positions : Cesium.Cartesian3.fromDegreesArray([
                        -95.0, 33.0,
                        -89.0, 33.0,
                        -89.0, 37.0,
                        -95.0, 37.0
                    ]),
                    holes : [{
                        positions : Cesium.Cartesian3.fromDegreesArray([
                            -93.0, 34.0,
                            -91.0, 34.0,
                            -91.0, 36.0,
                            -93.0, 36.0
                        ])
                    }]
                }]
            }]
        },
        material : Cesium.Color.BLUE,
        outline : true,
        outlineColor : Cesium.Color.BLACK
    }
});
多段线
(Polylines)
JavaScript
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
var redLine = viewer.entities.add({
    name : '沿着地球表面的红线',
    polyline : {
        positions : Cesium.Cartesian3.fromDegreesArray(
            [-75, 35,
             -125, 35]),
        width : 5,
        material : Cesium.Color.RED
    }
});
 
var glowingLine = viewer.entities.add({
    name : '具有发光效果的线',
    polyline : {
        positions : Cesium.Cartesian3.fromDegreesArray(
            [-75, 37, -125, 37]
        ),
        width : 10,
        material : new Cesium.PolylineGlowMaterialProperty({
            glowPower : 0.2,
            color : Cesium.Color.BLUE
        })
    }
});
 
var orangeOutlined = viewer.entities.add({
    name : '具有一定高度的线',
    polyline : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(
            [-75, 39, 250000,-125, 39, 250000]
        ),
        width : 5,
        material : new Cesium.PolylineOutlineMaterialProperty({
            color : Cesium.Color.ORANGE,
            outlineWidth : 2,
            outlineColor : Cesium.Color.BLACK
        })
    }
});
 
var yellowLine = viewer.entities.add({
    name : '不贴着地表的线',
    polyline : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(
            [-75, 43, 500000,-125, 43, 500000]
        ),
        width : 3,
        followSurface : false,  //是否贴着地表
        material : Cesium.Color.PURPLE
    }
});
多段线体
(Polyline Volumes)
JavaScript
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
var viewer = new Cesium.Viewer('cesiumContainer');
 
function computeCircle(radius) {
    var positions = [];
    for (var i = 0; i < 360; i++) {
        var radians = Cesium.Math.toRadians(i);
        positions.push(new Cesium.Cartesian2(
            radius * Math.cos(radians), radius * Math.sin(radians)));
    }
    return positions;
}
 
function computeStar(arms, rOuter, rInner) {
    var angle = Math.PI / arms;
    var length = 2 * arms;
    var positions = new Array(length);
    for (var i = 0; i < length; i++) {
        var r = (i % 2) === 0 ? rOuter : rInner;
        positions[i] = new Cesium.Cartesian2(
            Math.cos(i * angle) * r, Math.sin(i * angle) * r);
    }
    return positions;
}
 
var redTube = viewer.entities.add({
    name : 'Red tube with rounded corners',
    polylineVolume : {
        positions : Cesium.Cartesian3.fromDegreesArray(
            [-85.0, 32.0,
             -85.0, 36.0,
             -89.0, 36.0]),
        shape : computeCircle(60000.0),
        material : Cesium.Color.RED
    }
});
 
var greenBox = viewer.entities.add({
    name : 'Green box with beveled corners and outline',
    polylineVolume : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(
            [-90.0, 32.0, 0.0,
             -90.0, 36.0, 100000.0,
             -94.0, 36.0, 0.0]),
        shape :[new Cesium.Cartesian2(-50000, -50000),
                new Cesium.Cartesian2(50000, -50000),
                new Cesium.Cartesian2(50000, 50000),
                new Cesium.Cartesian2(-50000, 50000)],
        cornerType : Cesium.CornerType.BEVELED,
        material : Cesium.Color.GREEN,
        outline : true,
        outlineColor : Cesium.Color.BLACK
    }
});
 
var blueStar = viewer.entities.add({
    name : 'Blue star with mitered corners and outline',
    polylineVolume : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(
            [-95.0, 32.0, 0.0,
             -95.0, 36.0, 100000.0,
             -99.0, 36.0, 200000.0]),
        shape : computeStar(7, 70000, 50000),
        cornerType : Cesium.CornerType.MITERED,
        material : Cesium.Color.BLUE,
        outline : true,
        outlineColor : Cesium.Color.BLACK
    }
});
 
viewer.zoomTo(viewer.entities);
矩形
(Rectangles)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//红色矩形
var redRectangle = viewer.entities.add({
    name : 'Red translucent rectangle with outline',
    rectangle : {
        coordinates : Cesium.Rectangle.fromDegrees(-110.0, 20.0, -80.0, 25.0),
        material : Cesium.Color.RED.withAlpha(0.5),
        outline : true,
        outlineColor : Cesium.Color.RED
    }
});
//绿色旋转、拉伸的矩形
var greenRectangle = viewer.entities.add({
    name : 'Green translucent, rotated, and extruded rectangle',
    rectangle : {
        coordinates : Cesium.Rectangle.fromDegrees(-100.0, 30.0, -90.0, 40.0),
        material : Cesium.Color.GREEN.withAlpha(0.5),
        rotation : Cesium.Math.toRadians(45),
        extrudedHeight : 300000.0,
        height : 100000.0,
        outline : true,
        outlineColor : Cesium.Color.GREEN
    }
});
球和椭球
(Spheres Ellipsoids)
 
JavaScript
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
var blueEllipsoid = viewer.entities.add({
    name : 'Blue ellipsoid',
    position: Cesium.Cartesian3.fromDegrees(-114.0, 40.0, 300000.0),
    ellipsoid : {
        //可以指定三个轴的半径
        radii : new Cesium.Cartesian3(200000.0, 200000.0, 300000.0),
        material : Cesium.Color.BLUE
    }
});
 
var redSphere = viewer.entities.add({
    name : 'Red sphere with black outline',
    position: Cesium.Cartesian3.fromDegrees(-107.0, 40.0, 300000.0),
    ellipsoid : {
        //正球体
        radii : new Cesium.Cartesian3(300000.0, 300000.0, 300000.0),
        material : Cesium.Color.RED,
        outline : true,
        outlineColor : Cesium.Color.BLACK
    }
});
 
var outlineOnly = viewer.entities.add({
    name : 'Yellow ellipsoid outline',
    position: Cesium.Cartesian3.fromDegrees(-100.0, 40.0, 300000.0),
    ellipsoid : {
        radii : new Cesium.Cartesian3(200000.0, 200000.0, 300000.0),
        fill : false,
        outline : true,
        outlineColor : Cesium.Color.YELLOW,
        slicePartitions : 24, //横向切割线
        stackPartitions : 36  //纵向切割线
    }
});
墙
(Walls)
JavaScript
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
//东西方向的横墙
var redWall = viewer.entities.add({
    name : 'Red wall at height',
    wall : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(
             [-115.0, 44.0, 200000.0,//坐标点
              -90.0, 44.0, 200000.0]
        ),
        minimumHeights : [100000.0, 100000.0], //按坐标点的最小高度数组
        material : Cesium.Color.RED
    }
});
//四边围墙
var greenWall = viewer.entities.add({
    name : 'Green wall from surface with outline',
    wall : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(
            [-107.0, 43.0, 100000.0,
             -97.0, 43.0, 100000.0,
             -97.0, 40.0, 100000.0,
             -107.0, 40.0, 100000.0,
             -107.0, 43.0, 100000.0]),
        material : Cesium.Color.GREEN,
        outline : true,
        outlineColor : Cesium.Color.BLACK
    }
});
//曲折的墙
var blueWall = viewer.entities.add({
    name : 'Blue wall with sawtooth heights and outline',
    wall : {
        //坐标点,不指定高度
        positions : Cesium.Cartesian3.fromDegreesArray(
            [-115.0, 50.0,
             -112.5, 50.0,
             -110.0, 50.0,
             -107.5, 50.0,
             -105.0, 50.0,
             -102.5, 50.0,
             -100.0, 50.0,
             -97.5, 50.0,
             -95.0, 50.0,
             -92.5, 50.0,
             -90.0, 50.0]),
        maximumHeights : [ //上高
            100000, 200000, 100000, 200000, 100000, 200000,
            100000, 200000, 100000, 200000, 100000],
        minimumHeights : [  //下高
            0, 100000,  0, 100000, 0, 100000, 0, 100000, 0,
            100000, 0],
        material : Cesium.Color.BLUE,
        outline : true,
        outlineColor : Cesium.Color.BLACK
    }
});
材质(Material)与轮廓(Outline)

多数形状均支持通过一致的方式来设置属性、控制外观:

  1. fill:布尔型,用于指定目标形状是否被填充
  2. outline:布尔型,用于指定是否绘制形状的边缘
  3. material:如果fill为true,该属性可以控制填充的材质类型

一个例外是多段线,可以设置outlineWidth 、outlineColor、glowPower 等属性。

高度与拉伸(Extrusion)

所有的形状均默认均是沿着地表的,目前圆形、椭圆、矩形可以在一定高度浮空显示,或者拉伸为Volume。

需要注意:Cesium总是使用米、弧度、秒为度量单位。下面是一个例子:

JavaScript
1
2
wyoming.polygon.height = 200000;         //设置高度
wyoming.polygon.extrudedHeight = 250000; //设置拉伸高度
在Viewer中可用的Entity特性

除非显式禁用,点击实体后会显示SelectionIndicator小器件,以及一个信息框。通过设置Entity.description,可以在信息框中显示任何HTML内容。

镜头控制

zoomTo方法可以立即定位到某个位置,而flyTo则是通过动画方式转移到某个位置,这两个方法均可以传递EntityCollection对象,并且均是异步方法,返回一个Promises对象

默认情况下,镜头是朝北、45度倾斜查看地球。下面的代码可以让镜头朝东、倾斜三十度查看:

JavaScript
1
2
3
4
5
6
7
8
9
10
//镜头顺时针旋转九十度,即东向
var heading = Cesium.Math.toRadians(90);
//镜头倾斜30度俯视
var pitch = Cesium.Math.toRadians(-30);
viewer.zoomTo(wyoming, new Cesium.HeadingPitchRange(heading, pitch)).then(function(result){
    //执行完毕后,进行的动作
    if (result) { //如果镜头切换成功,则result=true
        viewer.selectedEntity = wyoming;
    }
});

有时需要镜头跟踪某个实体(使居中)而不是地球,可以使用如下代码:

JavaScript
1
2
wyoming.position = Cesium.Cartesian3.fromDegrees(-107.724, 42.68);
viewer.trackedEntity = wyoming;  //跟踪某个实体。如果调用zoomTo、flyTo自动取消跟踪
管理Entity

EntityCollection对象是一个从Entity Id到Entity的关联数组,其提供例如add、remove、removeAll之类的常规函数,用于添加或者删除某个Entity:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//添加一个实体,并且提供ID
viewer.entities.add({
  id : '182bdba4-2b3e-47ae-bf0b-83f6fde285fd'
});
//获取一个实体
var entity = viewer.entities.getById('uniqueId')
//获取一个实体,如果不存在则创建之
var entity = viewer.entities.getOrCreateEntity('uniqueId');
 
//当添加、删除、修改EntityCollection中的Entity时,可以获得事件通知
function onChanged(collection, added, removed, changed){
    //add、removed、changed是增删改的Entity数组
    for(var i = 0; i < added.length; i++) {
        
    }
}
viewer.entities.collectionChanged.addEventListener(onChanged);
 
//大批量操作时,临时禁用事件可以提高性能
viewer.entities.suspendEvents();
//执行各种Entity操作
viewer.entities.resumeEvents();
点、图标和标签

添加一个点、标签或者图标很简单:

JavaScript
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
var viewer = new Cesium.Viewer( 'cesiumContainer' );
 
var citizensBankPark = viewer.entities.add( {
    name : 'Citizens Bank Park',
    position : Cesium.Cartesian3.fromDegrees( -75.166493, 39.9060534 ),
    point : { //点
        pixelSize : 5,
        color : Cesium.Color.RED,
        outlineColor : Cesium.Color.WHITE,
        outlineWidth : 2
    },
    label : { //文字标签
        text : 'Citizens Bank Park',
        font : '14pt monospace',
        style : Cesium.LabelStyle.FILL_AND_OUTLINE,
        outlineWidth : 2,
        verticalOrigin : Cesium.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置
        pixelOffset : new Cesium.Cartesian2( 0, -9 )   //偏移量
    }
    billboard : { //图标
        image : 'http://localhost:81/images/2015/02-02/Philadelphia_Phillies.png',
        width : 64,
        height : 64
    },
} );
 
viewer.zoomTo( viewer.entities );
3D模型

Cesium支持glTF格式的3D模型,glTF是WebGL、 OpenGL ES、 OpenGL的一种运行时模型格式,在Cesium中创建3D模型很简单:

JavaScript
1
2
3
4
5
6
7
8
9
10
var viewer = new Cesium.Viewer('cesiumContainer');
var entity = viewer.entities.add({
    position : Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706),
    model : {
        uri : '../../SampleData/models/CesiumGround/Cesium_Ground.gltf'
    },
    scale : 1,//和原始大小相比的缩放比例
    minimumPixelSize :100 //最小尺寸,防止太小而看不见
});
viewer.trackedEntity = entity;

默认情况下,模型竖直放置、并且面向东面。可以指定四元组(Quaternion)给Entity.orientation属性,以改变放置的方向:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var viewer = new Cesium.Viewer('cesiumContainer');
var position = Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706); //位置
var heading = Cesium.Math.toRadians(45.0);//绕垂直于地心的轴旋转
var pitch = Cesium.Math.toRadians(15.0);  //绕纬度线旋转
var roll = Cesium.Math.toRadians(0.0);    //绕经度线旋转
var orientation = Cesium.Transforms.headingPitchRollQuaternion(position, heading, pitch, roll);
 
var entity = viewer.entities.add({
    position : position,
    orientation : orientation,
    model : {
        uri : '../../SampleData/models/CesiumGround/Cesium_Ground.gltf'
    }
});
viewer.trackedEntity = entity;

例子中的heading(yaw)、pitch、roll对应了绕Z(垂直轴)、Y(维度方向)、X(经度方向)进行旋转,正数表示顺时针旋转(由于相对运动,在浏览器上看起来是地球在逆时针旋转),可以参考下图理解(人面向北面,摇头heading、点头pitch、歪头roll):head-pitch-roll

属性系统

Cesium提供了一些快捷方式来设置属性,例如outline:true,但是尝试使用e.polygon.outline这样的形式来获取轮廓时,会得到一个ConstantProperty对象,如果不使用快捷方式,则需要编写更多的代码,例如:

JavaScript
1
2
polygon.outline = new Cesium.ConstantProperty(true);
polygon.outlineColor = new Cesium.ConstantProperty(Cesium.Color.BLACK);

所有属性的实例均是Property的子类型,引入属性类层次而不是使用基本类型的原因是,某些属性是随着时间而变化的。

要得到属性的原始值,需要调用Property.getValue()方法,例如:

1
2
//获取当前时间点,多边形轮廓是否存在
polygon.outline.getValue(viewer.clock.currentTime)
几何图形与外观

我们可以通过Primitive API来操控几何图形及其外观,或者绘制各种特殊的形状。需要先得到Scene对象,然后在其上添加Primitive对象:

JavaScript
1
2
3
4
5
6
7
8
var viewer = new Cesium.Viewer('cesiumContainer');
var scene = viewer.scene;
 
scene.primitives.add(new Cesium.RectanglePrimitive({
    //绘制矩形
    rectangle : Cesium.Rectangle.fromDegrees(-100.0, 20.0, -90.0, 30.0),
    material : Cesium.Material.fromType('Dot')  //设置材质
}));

Primitive由两个部分组成:

  1. 几何形状(Geometry):定义了Primitive的结构,例如三角形、线条、点等
  2. 外观(Appearance ):定义Primitive的着色(Sharding),包括GLSL(OpenGL着色语言,OpenGL Shading Language)顶点着色器和片段着色器( vertex and fragment shaders),以及渲染状态(render state)

Cesium支持以下几何图形:

几何图形   说明
BoxGeometry 立方体
BoxOutlineGeometry 仅有轮廓的立方体
CircleGeometry 圆形或者拉伸的圆形
CircleOutlineGeometry 只有轮廓的圆形
CorridorGeometry 走廊:沿着地表的多段线,且具有一定的宽度,可以拉伸到一定的高度
CorridorOutlineGeometry 只有轮廓的走廊
CylinderGeometry 圆柱、圆锥或者截断的圆锥
CylinderOutlineGeometry 只有轮廓的圆柱、圆锥或者截断的圆锥
EllipseGeometry 椭圆或者拉伸的椭圆
EllipseOutlineGeometry 只有轮廓的椭圆或者拉伸的椭圆
EllipsoidGeometry 椭球体
EllipsoidOutlineGeometry 只有轮廓的椭球体
RectangleGeometry 矩形或者拉伸的矩形
RectangleOutlineGeometry 只有轮廓的矩形或者拉伸的矩形
PolygonGeometry 多边形,可以具有空洞或者拉伸一定的高度
PolygonOutlineGeometry 只有轮廓的多边形
PolylineGeometry 多段线,可以具有一定的宽度
SimplePolylineGeometry 简单的多段线
PolylineVolumeGeometry 多段线柱体
PolylineVolumeOutlineGeometry 只有轮廓的多段线柱体
SphereGeometry 球体
SphereOutlineGeometry 只有轮廓的球体
WallGeometry 墙
WallOutlineGeometry 只有轮廓的墙

使用Geometry和Appearance 具有以下优势:

  1. 性能:绘制大量Primitive时,可以将其合并为单个Geometry以减轻CPU负担、更好的使用GPU。合并Primitive由web worker线程执行,UI保持响应性
  2. 灵活性:Geometry与Appearance 解耦,两者可以分别进行修改
  3. 低级别访问:易于编写GLSL 顶点、片段着色器、使用自定义的渲染状态 

同时,具有以下劣势:

  1. 需要编写更多地代码
  2. 需要对图形编程有更多的理解,特别是OpenGL的知识

使用来Geometry、Appearance 改写上面的例子,代码为:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var viewer = new Cesium.Viewer('cesiumContainer');
var scene = viewer.scene;
//GeometryInstance是Geometry的一个容器
var instance = new Cesium.GeometryInstance({
  geometry : new Cesium.RectangleGeometry({
    rectangle : Cesium.Rectangle.fromDegrees(-100.0, 20.0, -90.0, 30.0),
    vertexFormat : Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
  })
});
//使用抽象的Primitive而不是RectanglePrimitive
scene.primitives.add(new Cesium.Primitive({
  geometryInstances : instance,
  //使用该外观,可以使矩形覆盖在地球表面,或者悬浮一定的高度
  appearance : new Cesium.EllipsoidSurfaceAppearance({
    material : Cesium.Material.fromType('Dot')
  })
}));
合并几何图形(Combing Geometries)

合并多个GeometryInstances 为一个Primitive可以极大的提高性能,下面的例子创建了2592一颜色各异的矩形,覆盖整个地球 :

JavaScript
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
var viewer = new Cesium.Viewer( 'cesiumContainer' );
var scene = viewer.scene;
 
var instances = [];
 
for ( var lon = -180.0; lon < 180.0; lon += 5.0 )
{
    for ( var lat = -90.0; lat < 90.0; lat += 5.0 )
    {
        instances.push( new Cesium.GeometryInstance( {
            geometry : new Cesium.RectangleGeometry( {
                rectangle : Cesium.Rectangle.fromDegrees( lon, lat, lon + 5.0, lat + 5.0 )
            } ),
            attributes : {
                color : Cesium.ColorGeometryInstanceAttribute.fromColor( Cesium.Color.fromRandom( {
                    alpha : 0.5
                } ) )
            }
        } ) );
    }
}
 
scene.primitives.add( new Cesium.Primitive( {
    geometryInstances : instances, //合并
    //某些外观允许每个几何图形实例分别指定某个属性,例如:
    appearance : new Cesium.PerInstanceColorAppearance()
} ) );
选取几何图形(Picking)

即使多个 GeometryInstance被合并为单个Primitive,让然可以独立的被访问。我们可以为每一个GeometryInstance指定一个id,并且可以通过Scene.pick来判断该实例是否被选取:

JavaScript
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
var viewer = new Cesium.Viewer( 'cesiumContainer' );
var scene = viewer.scene;
 
var instance = new Cesium.GeometryInstance( {
    geometry : new Cesium.RectangleGeometry( {
        rectangle : Cesium.Rectangle.fromDegrees( -100.0, 30.0, -90.0, 40.0 )
    } ),
    id : 'rectangle-1',
    attributes : {
        color : Cesium.ColorGeometryInstanceAttribute.fromColor( Cesium.Color.RED )
    }
} );
 
scene.primitives.add( new Cesium.Primitive( {
    geometryInstances : instance,
    appearance : new Cesium.PerInstanceColorAppearance()
} ) );
 
var handler = new Cesium.ScreenSpaceEventHandler( scene.canvas );
//设置单击事件的处理句柄
handler.setInputAction( function( movement )
{
    var pick = scene.pick( movement.position );
    if ( Cesium.defined( pick ) && ( pick.id === 'rectangle-1' ) )
    {
        console.log( '矩形被选取' );
    }
}, Cesium.ScreenSpaceEventType.LEFT_CLICK );
几何图形实例(Geometry Instances)

上面的例子中,我们已经用到了GeometryInstances,注意GeometryInstance与Geometry的关系:前者是后者的容器,多个Instance可以共用一个Geometry,并且可以通过GeometryInstances.modelMatrix属性提供不同position、scale、rotate等位置、缩放、旋转信息。例如,下面的例子使用同一个Geometry绘制了两个Instance,一个位于另一个的上方:

JavaScript
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
var viewer = new Cesium.Viewer( 'cesiumContainer' );
var scene = viewer.scene;
 
var ellipsoidGeometry = new Cesium.EllipsoidGeometry( {
    vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
    radii : new Cesium.Cartesian3( 300000.0, 200000.0, 150000.0 )//三轴半径
} );
//下方的实例
var cyanEllipsoidInstance = new Cesium.GeometryInstance( {
    geometry : ellipsoidGeometry,
    modelMatrix : Cesium.Matrix4.multiplyByTranslation( Cesium.Transforms.eastNorthUpToFixedFrame( Cesium.Cartesian3.fromDegrees( -100.0, 40.0 ) ), new Cesium.Cartesian3( 0.0, 0.0, 150000.0 ) ),
    attributes : {
        color : Cesium.ColorGeometryInstanceAttribute.fromColor( Cesium.Color.CYAN )
    }
} );
//上方的实例
var orangeEllipsoidInstance = new Cesium.GeometryInstance( {
    geometry : ellipsoidGeometry,
    modelMatrix : Cesium.Matrix4.multiplyByTranslation( Cesium.Transforms.eastNorthUpToFixedFrame( Cesium.Cartesian3.fromDegrees( -100.0, 40.0 ) ), new Cesium.Cartesian3( 0.0, 0.0, 450000.0 ) ),
    attributes : {
        color : Cesium.ColorGeometryInstanceAttribute.fromColor( Cesium.Color.ORANGE )
    }
} );
 
scene.primitives.add( new Cesium.Primitive( {
    geometryInstances : [
        cyanEllipsoidInstance, orangeEllipsoidInstance
    ],
    appearance : new Cesium.PerInstanceColorAppearance( {
        translucent : false,
        closed : true
    } )
} ) );
更新单个GeometryInstance的属性

在添加到Primitive中以后,让然可以修改几何图形的某些属性:

  1. 颜色:如果Primitive设置了PerInstanceColorAppearance外观,则可以修改ColorGeometryInstanceAttribute类型的颜色
  2. 可见性:任何实例可以修改可见性

示例代码:

JavaScript
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
var viewer = new Cesium.Viewer( 'cesiumContainer' );
var scene = viewer.scene;
 
var circleInstance = new Cesium.GeometryInstance( {
    geometry : new Cesium.CircleGeometry( {
        center : Cesium.Cartesian3.fromDegrees( -95.0, 43.0 ),
        radius : 250000.0,
        vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
    } ),
    attributes : {
        color : Cesium.ColorGeometryInstanceAttribute.fromColor( new Cesium.Color( 1.0, 0.0, 0.0, 0.5 ) ),
        show : new Cesium.ShowGeometryInstanceAttribute( true ) //显示或者隐藏
    },
    id : 'circle'
} );
var primitive = new Cesium.Primitive( {
    geometryInstances : circleInstance,
    appearance : new Cesium.PerInstanceColorAppearance( {
        translucent : false,
        closed : true
    } )
} );
scene.primitives.add( primitive );
 
//定期修改颜色
setInterval( function()
{
    var attributes = primitive.getGeometryInstanceAttributes( 'circle' );//获取某个实例的属性集
    attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue( Cesium.Color.fromRandom( {
        alpha : 1.0
    } ) );
}, 2000 );
外观(Appearances)

Primitive由两个重要部分组成:几何图形实例、外观,一个Primitive只能有一个外观,而可以有多个实例。几何图形定义了结构,外观定义了每个像素被如何着色,外观可能使用材质(Material)。这些对象的关系如下图所示:highleveldesign

Cesium支持下表列出的外观:

 外观  说明
MaterialAppearance 支持各种Geometry类型的外观,支持使用材质来定义着色
EllipsoidSurfaceAppearance MaterialAppearance的一个版本。假设几何图形与地表是平行的,并且依此来进行顶点属性(vertex attributes)的计算
PerInstanceColorAppearance 让每个实例使用自定义的颜色来着色
PolylineMaterialAppearance 支持使用材质来着色多段线
PolylineColorAppearance 使用每顶点或者每片段(per-vertex or per-segment )的颜色来着色多段线

外观定义了需要在GPU上执行的完整的GLSL顶点、片段着色器,通常不需要修改这一部分,除非需要定义自己的外观。

外观还定义了完整的render state,用于在绘制Primitive时控制GPU的状态,可以直接或者通过高层API来定义render state:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//下面的外观可用于定义一个Viewer不可进入的不透明盒子
var appearance = new Cesium.PerInstanceColorAppearance( {
    translucent : false,
    closed : true
} );
//下面的代码效果同上
var translucent = new Cesium.PerInstanceColorAppearance( {
    renderState : {
        depthTest : {
            enabled : true
        },
        cull : {
            enabled : true,
            face : Cesium.CullFace.BACK
        }
    }
} );

一旦外观被创建,其render state就不可再变,但是其材质是可以替换的。另外Primitive的外观也是不可修改的。

大部分外观具有flat、faceForward属性,可以间接的控制GLSL 着色器:

  1. flat:扁平化着色,不考虑光线的作用
  2. faceForward:布尔值,控制光照效果
Geometry与Appearance的兼容性

需要注意,不是所有外观和所有几何图形可以搭配使用,例如EllipsoidSurfaceAppearance与WallGeometry就不能搭配,原因是后者是垂直于地表的。

即使外观与几何图形兼容,它们还必须有匹配的顶点格式(vertex formats)—— 即几何图形必须具有外观可以作为输入的数据格式,在创建Geometry时可以提供VertexFormat。

为了简便,可以让Geometry计算所有顶点属性(vertex attributes),以使之适用于任何外观,但这样做效率较差:

JavaScript
1
2
3
var geometry = new Cesium.RectangleGeometry( {
    vertexFormat : Cesium.VertexFormat.ALL
} );

 而如果我们使用外观EllipsoidSurfaceAppearance,其实只需要知道位置:

JavaScript
1
2
3
var geometry = new Ceisum.RectangleGeometry( {
    vertexFormat : Ceisum.VertexFormat.POSITION_ONLY
} );

大部分外观具有vertexFormat属性或者VERTEX_FORMAT 静态常量,创建形状时只需要使用这些顶点格式即可:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
var geometry = new Ceisum.RectangleGeometry( {
    vertexFormat : Ceisum.EllipsoidSurfaceAppearance.VERTEX_FORMAT
} );
 
var geometry2 = new Ceisum.RectangleGeometry( {
    vertexFormat : Ceisum.PerInstanceColorAppearance.VERTEX_FORMAT
} );
 
var appearance = new Ceisum.MaterialAppearance();
var geometry3 = new Ceisum.RectangleGeometry( {
    vertexFormat : appearance.vertexFormat
} );

此外,两个形状必须具有匹配的vertexFormat,才能被合并到一个Primitive中。

3D模型

我们可以转换、加载并且在Cesium中使用3D模型。Cesium支持glTF(一个新兴的Web 3D模型工业标准)格式的3D模型,并且提供在线的 COLLADA - glTF转换工具。Cesium针对3D模型支持关键帧动画、皮肤、单独节点选取等特性。

Cesium自带了三个模型:飞机、车辆、人。下面的例子载入一个车辆模型:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
var scene = viewer.scene;
//创建坐标
var coord = Cesium.Cartesian3.fromDegrees( -75.62898254394531, 40.02804946899414, 0.0 );
//创建一个东(X,红色)北(Y,绿色)上(Z,蓝色)的本地坐标系统
var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame( coord );
// 改变3D模型的模型矩阵,可以用于移动物体
// 物体的世界坐标 = 物体的模型坐标 * 世界矩阵
var model = scene.primitives.add( Cesium.Model.fromGltf( {//异步的加载模型
    url : '../../SampleData/models/CesiumGround/Cesium_Ground.gltf',
    modelMatrix : modelMatrix, //模型矩阵
    scale : 200.0 //缩放
} ) );

Cesium自带的3个模型已经内嵌了动画关键桢,如果需要播放动画,可以在调用Model.fromGltf后添加以下代码:

JavaScript
1
2
3
4
5
6
7
8
Cesium.when( model.readyPromise ).then( function( model )
{
    model.activeAnimations.addAll( {//播放模型中全部动画,如果需要播放单个动画,可以调用add,传入动画id
        loop : Cesium.ModelAnimationLoop.REPEAT, //直到被移出activeAnimations,一直播放
         speedup : 0.5,  //加速播放
         reverse : true  //逆序播放
    } );
} );

动画与Cesium的时钟系统同步化。

与其它Primitive一样,对3D模型的选取也是被支持的,当前点击的glTF node id、glTF mess一并被获取:

JavaScript
1
2
3
4
5
6
7
8
9
var handler = new Cesium.ScreenSpaceEventHandler( scene.canvas );
handler.setInputAction( function( movement )
{
    var pick = scene.pick( movement.endPosition );
    if ( Cesium.defined( pick ) && Cesium.defined( pick.node ) && Cesium.defined( pick.mesh ) )
    {
        console.log( 'node: ' + pick.node.name + '. mesh: ' + pick.mesh.name );
    }
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE );
栅格图层

Cesium支持多种标准化格式的GIS瓦片服务,可以把栅格图层绘制到地球的表面。这些图层的亮度、对比度、色相均可以动态调整:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//初始化一个查看器,并且提供一个栅格图层
var viewer = new Cesium.Viewer( 'cesiumContainer', {
    imageryProvider : new Cesium.ArcGisMapServerImageryProvider( {
        url : 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer'
    } ),
    baseLayerPicker : false
} );
//添加另外一个图层
var layers = viewer.scene.imageryLayers;
var blackMarble = layers.addImageryProvider( new Cesium.TileMapServiceImageryProvider( {
    url : '//cesiumjs.org/tilesets/imagery/blackmarble',
    maximumLevel : 8,
    credit : 'Black Marble imagery courtesy NASA Earth Observatory'
} ) );
//设置图层的透明度
blackMarble.alpha = 0.5;
//设置图层的亮度
blackMarble.brightness = 2.0;
 
//添加一个图层,在特定位置绘制一个图片
layers.addImageryProvider(new Cesium.SingleTileImageryProvider({
    url : '../images/Cesium_Logo_overlay.png',
    rectangle : Cesium.Rectangle.fromDegrees(-75.0, 28.0, -67.0, 29.75)
}));
3D地形图

Cesium支持3D地形图、水体特效,下面的代码添加该特性:

JavaScript
1
2
3
4
var terrainProvider = new Cesium.CesiumTerrainProvider( {
    url : '//assets.agi.com/stk-terrain/world'
} );
viewer.terrainProvider = terrainProvider;

需要注意的是,地形图、栅格图层是分别处理的,默认的栅格图层覆盖在地形图的上面。任何栅格图层均可与地形图搭配使用。

下面的代码可以启用光照、水体效果:

JavaScript
1
2
3
4
5
6
var terrainProvider = new Cesium.CesiumTerrainProvider( {
    url : '//assets.agi.com/stk-terrain/world',
    requestVertexNormals : true
} );
viewer.terrainProvider = terrainProvider;
viewer.scene.globe.enableLighting = true;
镜头

Cesium提供了以下默认鼠标行为:

  1. 单击并拖拽球体:旋转地球,镜头俯角不变
  2. 单击并拖拽空间:滚动roll、俯仰pitch镜头
  3. 右击并拖拽、中键滚动:缩放镜头
  4. 中键拖拽:沿着地表的点旋转镜头

调用camera.setView()可以设置相机的位置和方向:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
camera.setView( {
    positionCartographic : new Cesium.Cartographic( longitude, latitude, height ),
    heading : headingAngle,
    pitch : pitchAngle,
    roll : rollAngle
} );
 
//确保指定的东西南北范围进入视野
var west = Cesium.Math.toRadians( -77.0 );
var south = Cesium.Math.toRadians( 38.0 );
var east = Cesium.Math.toRadians( -72.0 );
var north = Cesium.Math.toRadians( 42.0 );
var extent = new Cesium.Extent( west, south, east, north );
camera.viewExtent( extent, Cesium.Ellipsoid.WGS84 );

Camera

相机对象表示当前镜头的位置(position)、方向(orientation)、参考坐标系(reference frame)、视见体(View Frustum)。

move*、zoom*方法用于沿着镜头的原点(orientation )或者一个给定的矢量来变换(translate)镜头的位置。移动过程中方向保持固定:direction-up-right

look*、twist*方法用于依照direction、up、right向量来旋转方向,旋转过程中位置保持不变:look-twist

rotate*方法用于依据给定的矢量来变换位置、旋转方向。

 
← ActiveMQ学习笔记
反应器模式 →
7 Comments On This Topic
  1. 回复
    tritont
    2018/03/28

    写的很好,谢谢

    • 回复
      Alex
      2018/03/29

      :D

  2. 回复
    cesium编程入门(十)优秀资源 | cesium中文网
    2018/03/30

    […] 6.绿色记忆 https://blog.gmem.cc/cesium-study-note […]

  3. 回复
    木遥
    2018/06/26

    很用心的教程

    • 回复
      Alex
      2018/06/26

      :D

  4. 回复
    Goldberg
    2019/03/14

    拜读并受教了。
    //让镜头飞行(动画)到某个地点和方向 此处有个小错误
    flyTo的属性complate

    • 回复
      Alex
      2019/03/14

      谢谢提醒

Leave a Reply to 朱哈哈 Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Related Posts

  • TileStache知识集锦
  • 使用Babel进行JS转码
  • 基于Kurento搭建WebRTC服务器
  • ExtJS 4的容器机制
  • 基于AngularJS开发Web应用

Recent Posts

  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
  • A Comprehensive Study of Kotlin for Java Developers
  • 背诵营笔记
  • 利用LangChain和语言模型交互
  • 享学营笔记
ABOUT ME

汪震 | Alex Wong

江苏淮安人,现居北京。目前供职于腾讯云,专注容器方向。

GitHub:gmemcc

Git:git.gmem.cc

Email:gmemjunk@gmem.cc@me.com

ABOUT GMEM

绿色记忆是我的个人网站,域名gmem.cc中G是Green的简写,MEM是Memory的简写,CC则是我的小天使彩彩名字的简写。

我在这里记录自己的工作与生活,同时和大家分享一些编程方面的知识。

GMEM HISTORY
v2.00:微风
v1.03:单车旅行
v1.02:夏日版
v1.01:未完成
v0.10:彩虹天堂
v0.01:阳光海岸
MIRROR INFO
Meta
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
Recent Posts
  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
    In this blog post, I will walk ...
  • A Comprehensive Study of Kotlin for Java Developers
    Introduction Purpose of the Study Understanding the Mo ...
  • 背诵营笔记
    Day 1 Find Your Greatness 原文 Greatness. It’s just ...
  • 利用LangChain和语言模型交互
    LangChain是什么 从名字上可以看出来,LangChain可以用来构建自然语言处理能力的链条。它是一个库 ...
  • 享学营笔记
    Unit 1 At home Lesson 1 In the ...
  • K8S集群跨云迁移
    要将K8S集群从一个云服务商迁移到另外一个,需要解决以下问题: 各种K8S资源的迁移 工作负载所挂载的数 ...
  • Terraform快速参考
    简介 Terraform用于实现基础设施即代码(infrastructure as code)—— 通过代码( ...
  • 草缸2021
    经过四个多月的努力,我的小小荷兰景到达极致了状态。

  • 编写Kubernetes风格的APIServer
    背景 前段时间接到一个需求做一个工具,工具将在K8S中运行。需求很适合用控制器模式实现,很自然的就基于kube ...
  • 记录一次KeyDB缓慢的定位过程
    环境说明 运行环境 这个问题出现在一套搭建在虚拟机上的Kubernetes 1.18集群上。集群有三个节点: ...
  • eBPF学习笔记
    简介 BPF,即Berkeley Packet Filter,是一个古老的网络封包过滤机制。它允许从用户空间注 ...
  • IPVS模式下ClusterIP泄露宿主机端口的问题
    问题 在一个启用了IPVS模式kube-proxy的K8S集群中,运行着一个Docker Registry服务 ...
  • 念爷爷
      今天是爷爷的头七,十二月七日、阴历十月廿三中午,老人家与世长辞。   九月初,回家看望刚动完手术的爸爸,发

  • 6 杨梅坑

  • liuhuashan
    深圳人才公园的网红景点 —— 流花山

  • 1 2020年10月拈花湾

  • 内核缺陷触发的NodePort服务63秒延迟问题
    现象 我们有一个新创建的TKE 1.3.0集群,使用基于Galaxy + Flannel(VXLAN模式)的容 ...
  • Galaxy学习笔记
    简介 Galaxy是TKEStack的一个网络组件,支持为TKE集群提供Overlay/Underlay容器网 ...
TOPLINKS
  • Zitahli's blue 91 people like this
  • 梦中的婚礼 64 people like this
  • 汪静好 61 people like this
  • 那年我一岁 36 people like this
  • 为了爱 28 people like this
  • 小绿彩 26 people like this
  • 彩虹姐姐的笑脸 24 people like this
  • 杨梅坑 6 people like this
  • 亚龙湾之旅 1 people like this
  • 汪昌博 people like this
  • 2013年11月香山 10 people like this
  • 2013年7月秦皇岛 6 people like this
  • 2013年6月蓟县盘山 5 people like this
  • 2013年2月梅花山 2 people like this
  • 2013年淮阴自贡迎春灯会 3 people like this
  • 2012年镇江金山游 1 people like this
  • 2012年徽杭古道 9 people like this
  • 2011年清明节后扬州行 1 people like this
  • 2008年十一云龙公园 5 people like this
  • 2008年之秋忆 7 people like this
  • 老照片 13 people like this
  • 火一样的六月 16 people like this
  • 发黄的相片 3 people like this
  • Cesium学习笔记 90 people like this
  • IntelliJ IDEA知识集锦 59 people like this
  • 基于Kurento搭建WebRTC服务器 38 people like this
  • Bazel学习笔记 37 people like this
  • PhoneGap学习笔记 32 people like this
  • NaCl学习笔记 32 people like this
  • 使用Oracle Java Mission Control监控JVM运行状态 29 people like this
  • Ceph学习笔记 27 people like this
  • 基于Calico的CNI 27 people like this
Tag Cloud
ActiveMQ AspectJ CDT Ceph Chrome CNI Command Cordova Coroutine CXF Cygwin DNS Docker eBPF Eclipse ExtJS F7 FAQ Groovy Hibernate HTTP IntelliJ IO编程 IPVS JacksonJSON JMS JSON JVM K8S kernel LB libvirt Linux知识 Linux编程 LOG Maven MinGW Mock Monitoring Multimedia MVC MySQL netfs Netty Nginx NIO Node.js NoSQL Oracle PDT PHP Redis RPC Scheduler ServiceMesh SNMP Spring SSL svn Tomcat TSDB Ubuntu WebGL WebRTC WebService WebSocket wxWidgets XDebug XML XPath XRM ZooKeeper 亚龙湾 单元测试 学习笔记 实时处理 并发编程 彩姐 性能剖析 性能调优 文本处理 新特性 架构模式 系统编程 网络编程 视频监控 设计模式 远程调试 配置文件 齐塔莉
Recent Comments
  • qg on Istio中的透明代理问题
  • heao on 基于本地gRPC的Go插件系统
  • 黄豆豆 on Ginkgo学习笔记
  • cloud on OpenStack学习笔记
  • 5dragoncon on Cilium学习笔记
  • Archeb on 重温iptables
  • C/C++编程:WebSocketpp(Linux + Clion + boostAsio) – 源码巴士 on 基于C/C++的WebSocket库
  • jerbin on eBPF学习笔记
  • point on Istio中的透明代理问题
  • G on Istio中的透明代理问题
  • 绿色记忆:Go语言单元测试和仿冒 on Ginkgo学习笔记
  • point on Istio中的透明代理问题
  • 【Maven】maven插件开发实战 – IT汇 on Maven插件开发
  • chenlx on eBPF学习笔记
  • Alex on eBPF学习笔记
  • CFC4N on eBPF学习笔记
  • 李运田 on 念爷爷
  • yongman on 记录一次KeyDB缓慢的定位过程
  • Alex on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • haolipeng on 基于本地gRPC的Go插件系统
  • 吴杰 on 基于C/C++的WebSocket库
©2005-2025 Gmem.cc | Powered by WordPress | 京ICP备18007345号-2