• Cesium入门-3-官方完整实例


    实例核心代码

    
    //资源访问令牌 Cesium token
    Cesium.Ion.defaultAccessToken='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4MWI5NTY0Mi1iOGE3LTQ3ZTMtOGQ4OC03NThiN2VkZGI4NTYiLCJpZCI6NzY2Niwic2NvcGVzIjpbImFzbCIsImFzciIsImFzdyIsImdjIl0sImlhdCI6MTU1MDIyNTM5OX0.2Abc9p46PA9kJ3E-BaKMXiyb0rvgo7AFUR1nR78VF7c'
    
    //创建Cesium 场景
    var viewer=new Cesium.Viewer('cesiumContainer',{
        scene3DOnly:true,
        selectionIndicator:true,
        baseLayerPicker:true,
        timeline:true,//时间轴
        animation:true,//动画轴
    });
    
    //增加地图图片资源提供者(CesiumIon) Cesium官方
    viewer.imageryLayers.remove(0);   //图片层级管理 移除默认的基础层级提供者
    viewer.imageryLayers.addImageryProvider(new Cesium.IonImageryProvider({assetId:3954}));
    
    
    //设置地形
    viewer.terrainProvider=Cesium.createWorldTerrain({
        requestWaterMask:true,//水渲染需求
        requestVertexNormals:true//顶点法线渲染需求
    });
    
    viewer.scene.globe.depthTestAgainstTerrain=true;//深度显示(用于湖泊河流 水深对周围景观的影响)
    viewer.scene.globe.enableLighting=true;//全局日照(受太阳,月亮的位置而影响光照信息)
    
    //创建初始化摄像机视图
    var initialPosition=new Cesium.Cartesian3.fromDegrees(-73.998114468289017509, 40.674512895646692812, 2631.082799425431);//摄像机位置 ,经度,纬度,高度
    var initialOrientation=new Cesium.HeadingPitchRoll.fromDegrees(7.1077496389876024807, -31.987223091598949054, 0.025883251314954971306);//飞行 专用的  表示旋转角度之类的东西: 飞行中飞机机体轴相对于地面的角位置
    var homeCameraView={
        destination:initialPosition,
        orientation:{
            heading:initialOrientation.heading, //偏航角
            pitch:initialOrientation.pitch,     //俯仰角
            roll:initialOrientation.roll    //滚转角
        }
    };
    viewer.scene.camera.setView(homeCameraView);
    
    
    //飞行时,相机的动画属性设置
    homeCameraView.dutaion=2.0;
    homeCameraView.maximumHeight=2000;
    homeCameraView.pitchAdjustHeight=2000;
    homeCameraView.endTransform=Cesium.Matrix4.IDENTITY;
    
    // //覆盖初始相机视图
    viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function(e){
        e.canvel=true;
        viewer.scene.camera.flyTo(homeCameraView)   //貌似没效果 -.-
    })
    
    
    //设置时间轴
    viewer.clock.shouldAnimate=true;//右下角圆盘指针控制的时钟动画
    viewer.clock.startTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z"); //开始时间 使用iso8601国际标准
    viewer.clock.stopTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:20:00Z");  //停止时间
    viewer.clock.currentTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z");//当前时间
    viewer.clock.multiple=2; //时间流逝 速率
    viewer.clock.clockStep=Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER;//时钟的 步长
    viewer.clock.clockRange=Cesium.ClockRange.LOOP_STOP;//循环
    viewer.timeline.zoomTo(viewer.clock.startTime,viewer.clock.stopTime);//设置时间轴可见趋近
    
    /**加载KML数据--添加地理标记  从KML文件中获取数据 由Cesium.KmlDataSource数据加载器加载--**/
    var kmlOptions = {
        camera : viewer.scene.camera,
        canvas : viewer.scene.canvas,
        clampToGround : true
    };
    // 从KML 文件中加载地理标记点 geocache
    //KML全称:Keyhole Markup Language,是基于XML(eXtensible Markup Language,可扩展标记语言)语法标准的一种标记语言(markup language),由Google(谷歌)旗下的Keyhole公司发展并维护,用来表达地理标记
    var geocachePromise = Cesium.KmlDataSource.load('https://gist.githubusercontent.com/rahwang/bf8aa3a46da5197a4c3445c5f5309613/raw/04e17770dd552fd2694e2597986fd480b18b5014/sampleGeocacheLocations.kml', kmlOptions);
    
    // 从geocachePromise中解析标记点 并转化为  Cesium中的 实体对象(entity)
    geocachePromise.then(function(dataSource) {
        //数据源添加到实际场景viewer 中的dataSources数据源中
        viewer.dataSources.add(dataSource);
    
        // Get the array of entities
        var geocacheEntities = dataSource.entities.values;
    
        for (var i = 0; i < geocacheEntities.length; i++) {
            var entity = geocacheEntities[i];
            if (Cesium.defined(entity.billboard)) {
                // Adjust the vertical origin so pins sit on terrain
                entity.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
                // Disable the labels to reduce clutter
                entity.label = "KML billboard 兴趣点"+i;
                // Add distance display condition  满足的距离条件时,显示兴趣点
                entity.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(10.0, 20000.0);
                // Compute latitude and longitude in degrees 位置和角度
                var cartographicPosition = Cesium.Cartographic.fromCartesian(entity.position.getValue(Cesium.JulianDate.now()));
                //转化成经纬度
                var latitude = Cesium.Math.toDegrees(cartographicPosition.latitude);
                var longitude = Cesium.Math.toDegrees(cartographicPosition.longitude);
                // Modify description  兴趣点属性 描述
                var description = '<table class="cesium-infoBox-defaultTable cesium-infoBox-defaultTable-lighter"><tbody>';
                description += '<tr><th>' + "Latitude" + '</th><td>' + latitude + '</td></tr>';
                description += '<tr><th>' + "Longitude" + '</th><td>' + longitude + '</td></tr>';
                description += '</tbody></table>';
                entity.description = description;
            }
        }
    });
    
    /**加载GeoJson数据 ,添加邻近区图形  从GeoJson文件中获取数据 由GeoJsonDataSource数据加载器加载**/
    var geojsonOptions = {
        clampToGround : true
    };
    // 从Geojson文件中获取 多边形 边界信息数据
    var neighborhoodsPromise = Cesium.GeoJsonDataSource.load('https://gist.githubusercontent.com/rahwang/2c421916bb955ca722a4dbc8ab079c76/raw/ae8a1c5680fbd2fc6940dd3a8f941ad397bdc085/sampleNeighborhoods.geojson', geojsonOptions);
    
    //从neighborhoodsPromise 数据源转化为Cesium中的数据实体entity
    var neighborhoods;
    neighborhoodsPromise.then(function(dataSource) {
        // 数据源添加到实际场景viewer 中的dataSources数据源中
        viewer.dataSources.add(dataSource);
        neighborhoods = dataSource.entities;
    
        // 获取总的数据实体 数组
        var neighborhoodEntities = dataSource.entities.values;
        for (var i = 0; i < neighborhoodEntities.length; i++) {
            var entity = neighborhoodEntities[i];
    
            if (Cesium.defined(entity.polygon)) {
                // Use kml neighborhood value as entity name
                entity.name = entity.properties.neighborhood;
                // 设置多边形 的材质 和透明
                entity.polygon.material = Cesium.Color.fromRandom({
                    red : 0.1,
                    maximumGreen : 0.5,
                    minimumBlue : 0.5,
                    alpha : 0.6
                });
                // Tells the polygon to color the terrain. ClassificationType.CESIUM_3D_TILE will color the 3D tileset, and ClassificationType.BOTH will color both the 3d tiles and terrain (BOTH is the default)
                entity.polygon.classificationType = Cesium.ClassificationType.TERRAIN;
                // 计算生成polygon的中心位置
                var polyPositions = entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
                var polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center;
                polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter);
                entity.position = polyCenter;
                // 实体标签 显示的信息设置
                entity.label = {
                    text : entity.name,//文字
                    showBackground : false,//背景
                    scale : 0.6,//标签缩放大小
                    horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
                    distanceDisplayCondition : new Cesium.DistanceDisplayCondition(10.0, 8000.0),
                    disableDepthTestDistance : Number.POSITIVE_INFINITY
                };
            }
        }
    });
    
    /**加载Czml数据 ,从czml文件中 由Cesium.CzmlDataSource 数据加载器加载飞行路径信息**/
    // 从czml文件中加载数据
    var dronePromise = Cesium.CzmlDataSource.load('https://gist.githubusercontent.com/rahwang/0d1afa6f9e5aa342cb699d26851d97df/raw/5fec1c0cebc097661579143096e796a097c9b629/sampleFlight.czml');
    // Save a new drone model entity
    var drone;
    dronePromise.then(function(dataSource) {
    
        viewer.dataSources.add(dataSource);
        drone = dataSource.entities.values[0];
        // 加载一个gtlf格式的3D模型
        drone.model = {
            uri : 'https://gist.githubusercontent.com/rahwang/9843cb77fc1c6d07c287566ed4e08ee3/raw/dc3a9ff6fc73b784519ac9371c0e2cbd3ab3dc47/CesiumDrone.gltf',
            minimumPixelSize : 128,
            maximumScale : 2000
        };
        // 实时计算飞行时,模型的巡航角度
        drone.orientation = new Cesium.VelocityOrientationProperty(drone.position);
    
        // 圆滑路径,使路径相对平滑过渡 插值过渡
        drone.position.setInterpolationOptions({
            interpolationAlgorithm : Cesium.HermitePolynomialApproximation, //插值算法
            interpolationDegree : 2
        });
        //3D笛卡尔坐标点
        drone.viewFrom = new Cesium.Cartesian3(-30, 0, 0);
    });
    
    
    /**加载3dTile 数据集 瓦片数据  ,其实就是景观建筑群数据**/
    var city = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({ url: Cesium.IonResource.fromAssetId(3839) }));//我账号没有该地理资源。。。
    
    // Adjust the tileset height so it's not floating above terrain
    var heightOffset = -32;
    city.readyPromise.then(function(tileset) {
        //3D瓦片的position 位置
        var boundingSphere = tileset.boundingSphere;
        var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
        var surfacePosition = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
        var offsetPosition = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
        var translation = Cesium.Cartesian3.subtract(offsetPosition, surfacePosition, new Cesium.Cartesian3());
        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    });
    
    //定义Tile样式
    // Define a white, opaque building style
    var defaultStyle = new Cesium.Cesium3DTileStyle({
        color : "color('white')",
        show : true
    });
    
    // Define a white, transparent building style
    var transparentStyle = new Cesium.Cesium3DTileStyle({
        color : "color('white', 0.3)",
        show : true
    });
    
    // Define a style in which buildings are colored by height 针对不同高度给与不同的样式
    var heightStyle = new Cesium.Cesium3DTileStyle({
        color : {
            conditions : [
                ["${height} >= 300", "rgba(45, 0, 75, 0.5)"],
                ["${height} >= 200", "rgb(102, 71, 151)"],
                ["${height} >= 100", "rgb(170, 162, 204)"],
                ["${height} >= 50", "rgb(224, 226, 238)"],
                ["${height} >= 25", "rgb(252, 230, 200)"],
                ["${height} >= 10", "rgb(248, 176, 87)"],
                ["${height} >= 5", "rgb(198, 106, 11)"],
                ["true", "rgb(127, 59, 8)"]
            ]
        }
    });
    
    // Set the tileset style to default 最终设置给tile的样式
    city.style = defaultStyle;
    
    
    
    //鼠标事件互动
    var previousPickedEntity;
    var handler=viewer.screenSpaceEventHandler;//在屏幕空间发生的事件柄
    handler.setInputAction(function(movement){
        var pickedPrimitive=viewer.scene.pick(movement.endPosition);//拾取对象
        var pickedEntity=Cesium.defined(pickedPrimitive)?pickedPrimitive.id:undefined;
        //高亮挑选的实体对象
        if(Cesium.defined(previousPickedEntity)){
            previousPickedEntity.billboard.scale=1.0;
            previousPickedEntity.billboard.color=Cesium.Color.WHITE;
        }
        // //高亮当前拾取的Entity对象
        if (Cesium.defined(pickedEntity) && Cesium.defined(pickedEntity.billboard)) {
            pickedEntity.billboard.scale = 2.0;
            pickedEntity.billboard.color = Cesium.Color.ORANGERED;
            previousPickedEntity = pickedEntity;
        }
    
    },Cesium.ScreenSpaceEventType.MOUSE_MOVE);//鼠标移动事件
    
    
    //切换相机
    var freeModeElement=document.getElementById('freeMode');//获取dom元素
    var droneModeElement=document.getElementById('droneMode');
    freeModeElement.addEventListener('change',setViewMode);
    droneModeElement.addEventListener('change',setViewMode);
    function setViewMode(){
        if(droneModeElement.checked){
            viewer.trackedEntity=drone//相机跟踪实体对象
        }else{
            viewer.trackedEntity=undefined;
            viewer.scene.camera.flyTo(homeCameraView);
        }
    }
    
    //用户双击实体是,会自动跟踪实体,可以添加一些处理Ui的逻辑
    viewer.trackedEntityChanged.addEventListener(function(){
        if (viewer.trackedEntity === drone) {
            freeModeElement.checked = false;
            droneModeElement.checked = true;
        }
    } )
    
    
    //同理设置一些显示
    var shadowsElement = document.getElementById('shadows');
    var neighborhoodsElement =  document.getElementById('neighborhoods');
    shadowsElement.addEventListener('change', function (e) {
        viewer.shadows = e.target.checked;//场景是否阴影
    });
    
    neighborhoodsElement.addEventListener('change', function (e) {
        neighborhoods.show = e.target.checked;//polygon 邻近区图形是否显示
    });
    
    //加载城市建筑群数据完成,关掉遮罩层,我账号无此资源,直接注释
    // // Finally, wait for the initial city to be ready before removing the loading indicator.
    // var loadingIndicator = document.getElementById('loadingIndicator');
    // loadingIndicator.style.display = 'block';
    // city.readyPromise.then(function () {
    //     loadingIndicator.style.display = 'none';//
    // });
    
    

    重要知识点

    创建场景

    创建地形

    • Cesium.CesiumTerrainProvider 地形提供者
     let viewer=new Cesium.Viewer('cesiumContainer',{//世界地形
              terrainProvider:new Cesium.CesiumTerrainProvider({
                  url:Cesium.IonResource.fromAssetId(1),
                  requestWaterMask:true,//水效果
                  requestVertexNormals: true//顶点法线效果
              })
          })
    

    添加图片层级(图片资源提供者xxxImageryProvider)

    创建初始化摄像机视图

    加载数据

    • KML数据加载
        var geocachePromise = Cesium.KmlDataSource.load(“URL”)
      
    • 加载GeoJson数据 ,添加邻近区图形
        var neighborhoodsPromise = Cesium.GeoJsonDataSource.load("URL")
      
    • CZML数据加载
        var dronePromise = Cesium.CzmlDataSource.load("URL")
      
    • 3DTile 瓦片数据加载 (景观,建筑群,)
        var city = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({ url: Cesium.IonResource.fromAssetId(3839) }));
      

    3DTile样式定义

    •   var defaultStyle = new Cesium.Cesium3DTileStyle({
              color : "color('white')",
              show : true
        });
      
    • // Define a style in which buildings are colored by height 针对不同高度给与不同的样式var heightStyle = new Cesium.Cesium3DTileStyle({
      color : {
          conditions : [
              ["${height} >= 300", "rgba(45, 0, 75, 0.5)"],
              ["${height} >= 200", "rgb(102, 71, 151)"],
              ["${height} >= 100", "rgb(170, 162, 204)"],
              ["${height} >= 50", "rgb(224, 226, 238)"],
              ["${height} >= 25", "rgb(252, 230, 200)"],
              ["${height} >= 10", "rgb(248, 176, 87)"],
              ["${height} >= 5", "rgb(198, 106, 11)"],
              ["true", "rgb(127, 59, 8)"]
          ]
      }});
      
    •   // Set the tileset style to default 最终设置给tile的样式
        city.style = defaultStyle;
      

    事件互动

    • 获取事件柄
        var handler=viewer.screenSpaceEventHandler;//在屏幕空间发生的事件柄
      
    • 事件处理

      handler.setInputAction(处理函数,具体事件)

            handler.setInputAction(function(movement){
        var pickedPrimitive=viewer.scene.pick(movement.endPosition);//拾取对象
        var pickedEntity=Cesium.defined(pickedPrimitive)?pickedPrimitive.id:undefined;
        //高亮挑选的实体对象
        if(Cesium.defined(previousPickedEntity)){
            previousPickedEntity.billboard.scale=1.0;
            previousPickedEntity.billboard.color=Cesium.Color.WHITE;
        }
        // //高亮当前拾取的Entity对象
        if (Cesium.defined(pickedEntity) && Cesium.defined(pickedEntity.billboard)) {
            pickedEntity.billboard.scale = 2.0;
            pickedEntity.billboard.color = Cesium.Color.ORANGERED;
            previousPickedEntity = pickedEntity;
        }
    
    },Cesium.ScreenSpaceEventType.MOUSE_MOVE);//鼠标移动事件
    
  • 相关阅读:
    python起航
    【Git】rebase 用法小结
    使用AutoJs编写UI的踩坑记录
    cpu性能消耗分析
    python自动安装依赖模块_python模块管理:如何自动生成和安装requirements.txt依赖...
    Office Tools Plus
    Git 仓库基础操作
    jmeter-阶梯式压测
    JMeter ServerAgent服务器资源监控插件
    Fastjson 从JSON字符串中取值 操作示例
  • 原文地址:https://www.cnblogs.com/telwanggs/p/11289313.html
Copyright © 2020-2023  润新知