Cesium⼊门-3-官⽅完整实例
实例核⼼代码
//资源访问令牌 Cesium token
Cesium.Ion.defaultAccessToken='JqdGkiOiI4MWI5NTY0Mi1iOGE3LTQ3ZTMtOGQ4OC03NThiN2VkZGI4NTYiLCJpZCI6NzY2Niwic2NvcGVzIjpbImFzbCIsImFzciIsImFzdyIsImdjIl0sImlhdCI6MTU1MD //创建Cesium 场景
var viewer=new Cesium.Viewer('cesiumContainer',{
scene3DOnly:true,
selectionIndicator:true,
baseLayerPicker:true,
timeline:true,//时间轴
animation:true,//动画轴
});
//增加地图图⽚资源提供者(CesiumIon) Cesium官⽅
ve(0);  //图⽚层级管理移除默认的基础层级提供者
viewer.imageryLayers.addImageryProvider(new Cesium.IonImageryProvider({assetId:3954}));
//设置地形
requestWaterMask:true,//⽔渲染需求
requestVertexNormals:true//顶点法线渲染需求
});
viewer.scene.globe.depthTestAgainstTerrain=true;//深度显⽰(⽤于湖泊河流⽔深对周围景观的影响)
viewer.ableLighting=true;//全局⽇照(受太阳,⽉亮的位置⽽影响光照信息)
//创建初始化摄像机视图
var initialPosition=new Cesium.Cartesian3.fromDegrees(-73.998114468289017509, 40.674512895646692812, 2631.0827********);//摄像机位置,经度,纬度,⾼度
var initialOrientation=new Cesium.HeadingPitchRoll.fromDegrees(7.1077496389876024807, -31.987223091598949054, 0.025883251314954971306);//飞⾏专⽤的表⽰旋转⾓度之类的东西:飞⾏中飞机机体轴相对于地⾯的⾓位置
var homeCameraView={
destination:initialPosition,
orientation:{
heading:initialOrientation.heading, //偏航⾓
pitch:initialOrientation.pitch,    //俯仰⾓
ll    //滚转⾓
}
};
viewer.scene.camera.setView(homeCameraView);
//飞⾏时,相机的动画属性设置
homeCameraView.dutaion=2.0;
homeCameraView.maximumHeight=2000;
homeCameraView.pitchAdjustHeight=2000;
// //覆盖初始相机视图
viewer.homeButton.viewModelmand.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;//循环
To(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('gist.githubusercontent/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 = ities.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(Value(w()));
//转化成经纬度
var latitude = Degrees(cartographicPosition.latitude);
var longitude = Degrees(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⽂件中获取多边形边界信息数据
3tilesvar neighborhoodsPromise = Cesium.GeoJsonDataSource.load('gist.githubusercontent/rahwang/2c421916bb955ca722a4dbc8ab079c76/raw/json', geojsonOptio //从neighborhoodsPromise 数据源转化为Cesium中的数据实体entity
var neighborhoods;
neighborhoodsPromise.then(function(dataSource) {
// 数据源添加到实际场景viewer 中的dataSources数据源中
viewer.dataSources.add(dataSource);
neighborhoods = ities;
// 获取总的数据实体数组
var neighborhoodEntities = ities.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 = ighborhood;
// 设置多边形的材质和透明
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.Value(w()).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('gist.githubusercontent/rahwang/0d1afa6f9e5aa342cb699d26851d97df/raw/l');
// Save a new drone model entity
var drone;
dronePromise.then(function(dataSource) {
viewer.dataSources.add(dataSource);
drone = ities.values[0];
// 加载⼀个gtlf格式的3D模型
uri : 'gist.githubusercontent/rahwang/9843cb77fc1c6d07c287566ed4e08ee3/raw/dc3a9ff6fc73b784519ac9371c0e2cbd3ab3dc47/CesiumDrone.gltf',
minimumPixelSize : 128,
maximumScale : 2000
};
// 实时计算飞⾏时,模型的巡航⾓度
// 圆滑路径,使路径相对平滑过渡插值过渡
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;
//3D⽡⽚的position 位置
var boundingSphere = tileset.boundingSphere;
var cartographic = Cesium.Cartographic.);
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());
});
/
/定义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.dPosition);//拾取对象
var pickedEntity=Cesium.defined(pickedPrimitive)?pickedPrimitive.id:undefined;
//⾼亮挑选的实体对象
if(Cesium.defined(previousPickedEntity)){
previousPickedEntity.billboard.scale=1.0;
lor=Cesium.Color.WHITE;
}
// //⾼亮当前拾取的Entity对象
if (Cesium.defined(pickedEntity) && Cesium.defined(pickedEntity.billboard)) {
pickedEntity.billboard.scale = 2.0;
lor = Cesium.Color.ORANGERED;
previousPickedEntity = pickedEntity;
}
},Cesium.ScreenSpaceEventType.MOUSE_MOVE);//⿏标移动事件
//切换相机
var ElementById('freeMode');//获取dom元素
var ElementById('droneMode');
freeModeElement.addEventListener('change',setViewMode);
droneModeElement.addEventListener('change',setViewMode);
function setViewMode(){
if(droneModeElement.checked){
}else{
viewer.scene.camera.flyTo(homeCameraView);
}
}
//⽤户双击实体是,会⾃动跟踪实体,可以添加⼀些处理Ui的逻辑
if (ackedEntity === drone) {
freeModeElement.checked = false;
droneModeElement.checked = true;
}
} )
/
/同理设置⼀些显⽰
var shadowsElement = ElementById('shadows');
var neighborhoodsElement =  ElementById('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 = ElementById('loadingIndicator');
// loadingIndicator.style.display = 'block';
// adyPromise.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.dPosition);//拾取对象
var pickedEntity=Cesium.defined(pickedPrimitive)?pickedPrimitive.id:undefined;
/
/⾼亮挑选的实体对象
if(Cesium.defined(previousPickedEntity)){
previousPickedEntity.billboard.scale=1.0;
lor=Cesium.Color.WHITE;
}
// //⾼亮当前拾取的Entity对象
if (Cesium.defined(pickedEntity) && Cesium.defined(pickedEntity.billboard)) {
pickedEntity.billboard.scale = 2.0;
lor = Cesium.Color.ORANGERED;
previousPickedEntity = pickedEntity;
}
},Cesium.ScreenSpaceEventType.MOUSE_MOVE);//⿏标移动事件
本⽂由创作,采⽤国际许可协议进⾏许可
本站⽂章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2019/02/20 20:19

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。