Cesium.Ion.defaultAccessToken = 'eyJhTlA';
var viewer = new Cesium.Viewer('cesiumContainer',{
terrainProvider : Cesium.createWorldTerrain({
requestWaterMask : true,
requestVertexNormals : true
}),
scene3DOnly : true,
//selectionIndicator : false,
//baseLayerPicker : false
} );
//打开深度测试,那么在地形以下的对象不可见
viewer.scene.globe.depthTestAgainstTerrain = true;
//开启全球光照
//viewer.scene.globe.enableLighting = true;
//创建相机初始位置和朝向
var initialPosition = new Cesium.Cartesian3.fromDegrees(-73.998,40.674,0);
var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(7.1,-31.987,0);
var homeCameraView = {
destination : initialPosition,
orientation : {
heading : initialOrientation.heading,
pitch : initialOrientation.pitch,
roll : initialOrientation.roll
}
};
//设置视图
//viewer.scene.camera.setView(homeCameraView);
//增加相机飞行动画参数
homeCameraView.duration = 2.0;
homeCameraView.maximumHeight = 2000;
homeCameraView.pitchAdjustHeight = 2000;
homeCameraView.endTransform = Cesium.Matrix4.IDENTITY;
//重新默认的home按钮
viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function(e){
e.cancel = true;
viewer.scene.camera.flyTo(homeCameraView);
});
//设置时钟和时间线
//启动动画
viewer.clock.shouldAnimate = true;
viewer.clock.startTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z");
viewer.clock.stopTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:20:00Z");
viewer.clock.currentTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z");
//设置加速率
viewer.clock.multiplier = 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);
var kmlOptions = {
camera : viewer.scene.camera,
canvas : viewer.scene.canvas,
//是否贴地
// clampToGround : true
};
//从KML的URL里加载POI点位
var geocachePromise = Cesium.KmlDataSource.load('http://localhost:8080/apps/SampleData/sampleGeocacheLocations.kml',kmlOptions);
//回调
geocachePromise.then(function(dataSource){
//把所有的entities添加到viewer里显示
viewer.dataSources.add(dataSource);
//获得entity列表
var geocacheEntites = dataSource.entities.values;
for(var i = 0; i < geocacheEntites.length; i++)
{
var entity = geocacheEntites[i];
if(Cesium.defined(entity.billboard))
{
//调整垂直方向的原点,保证图标里的针尖对着地表位置
entity.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
//去掉文字的显示
entity.label = undefined;
//设置可见距离
entity.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(10.0,20000.0);
//计算经纬度(角度表示)
var cartographicPosition = Cesium.Cartographic.fromCartesian(entity.position.getValue());
var longitude = Cesium.Math.toDegrees(cartographicPosition.longitude);
var latitude = Cesium.Math.toDegrees(cartographicPosition.latitude);
}
}
});
//行政区域多边形
var geojsonOptions = {
clampToGround : true
};
//从geojson文件加载行政区多边形边界数据
var neighborhoodPromise = Cesium.GeoJsonDataSource.load('http://localhost:8080/apps/sampleData/sampleNeighborhoods.geojson',geojsonOptions);
var neighborhoods;
neighborhoodPromise.then(function(dataSource){
viewer.dataSources.add(dataSource);
neighborhoods = dataSource.entities;
//获取enty列表遍历
var neighthoodEntities = dataSource.entities.values;
for(var i = 0; i < neighthoodEntities.length; i++)
{
var entity = neighthoodEntities[i];
if(Cesium.defined(entity.polygon))
{
//设置样式代码
entity.name = entity.properties.neighborhood;
//设置一个随机半透明颜色
entity.polygon.material = Cesium.Color.fromRandom({
red : 0.1,
maximumGreen : 0.5,
minimumBlue : 0.5,
alpha : 0.6
});
//设置让多边形贴地
entity.polygon.heightReference = Cesium.heightReference.CLAMP_TO_GROUND;
//获取多边形的positions列表,并计算它的中心点
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 : true,
scale : 0.6,
horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
distanceDisplayCondition : new Cesium.DistanceDisplayCondition(10.0, 8000.0),
disableDepthTestDistance : 100.0
};
}
}
});
//从CZML中载入无人机轨迹
var dronePromise = Cesium.CzmlDataSource.load('http://localhost:8080/apps/sampleData/sampleFlight.czml');
var drone;
dronePromise.then(function(dataSource){
viewer.dataSources.add(dataSource);
//使用id获取在CZML数据中定义的无人机entity
drone = dataSource.entities.getById('Aircraft/Aircraft1');
//附加一些三维模型
drone.model = {
uri : 'http://localhost:8080/apps/sampleData/models/CesiumDrone.gltf',
minimumPixelSize : 128,
maximumScale : 1000,
silhouetteColor : Cesium.Color.WHITE,
silhouetteSize : 2
};
//基于无人机轨迹的位置点,自动计算朝向
drone.orientation = new Cesium.VelocityOrientationProperty(drone.position);
//光滑的飞行路径
drone.position.setInterpolationOptions({
interpolationDegree : 3,
interpolationAlgorithm : Cesium.HermitePolynomialApproximation
});
//跟踪无人机
viewer.trackedEntity = drone;
//取消跟踪无人机
viewer.trackedEntity = undefined;
viewer.scene.camera.flyTo(homeCameraView);
});
//加载3dtiles建筑物模型
var tileset =viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
url : 'http://localhost:8080/apps/sampleData/Cesium3DTiles/Tilesets/Tileset/tileset.json'
//url : Cesium.IonResource.fromAssetId(3839)
}));
var defaultStyle = new Cesium.Cesium3DTileStyle({
color : 'rgba(255,255,255,0.5)',
show : true
});
tileset.style = defaultStyle;
//视点看向3dtile模型
viewer.zoomTo(tileset);
//鼠标移动事件
var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(function(evt){
console.log(evt.position);
var feature = viewer.scene.pick(evt.position);
if(feature instanceof Cesium.Cesium3DTileFeature){
var propertyNames = feature.getPropertyNames();
var length = propertyNames.length;
for(var i = 0; i < length; i++) {
//得到ID
var propertyName = propertyNames[i];
console.log(propertyName +":"+ feature.getProperty(propertyName));
propertyName.billboard.scale = 2.0;
}
}
},
Cesium.ScreenSpaceEventType.LEFT_CLICK);
var viewer = new Cesium.Viewer('cesiumContainer',{
terrainProvider : Cesium.createWorldTerrain({
requestWaterMask : true,
requestVertexNormals : true
}),
scene3DOnly : true,
//selectionIndicator : false,
//baseLayerPicker : false
} );
//打开深度测试,那么在地形以下的对象不可见
viewer.scene.globe.depthTestAgainstTerrain = true;
//开启全球光照
//viewer.scene.globe.enableLighting = true;
//创建相机初始位置和朝向
var initialPosition = new Cesium.Cartesian3.fromDegrees(-73.998,40.674,0);
var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(7.1,-31.987,0);
var homeCameraView = {
destination : initialPosition,
orientation : {
heading : initialOrientation.heading,
pitch : initialOrientation.pitch,
roll : initialOrientation.roll
}
};
//设置视图
//viewer.scene.camera.setView(homeCameraView);
//增加相机飞行动画参数
homeCameraView.duration = 2.0;
homeCameraView.maximumHeight = 2000;
homeCameraView.pitchAdjustHeight = 2000;
homeCameraView.endTransform = Cesium.Matrix4.IDENTITY;
//重新默认的home按钮
viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function(e){
e.cancel = true;
viewer.scene.camera.flyTo(homeCameraView);
});
//设置时钟和时间线
//启动动画
viewer.clock.shouldAnimate = true;
viewer.clock.startTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z");
viewer.clock.stopTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:20:00Z");
viewer.clock.currentTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z");
//设置加速率
viewer.clock.multiplier = 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);
var kmlOptions = {
camera : viewer.scene.camera,
canvas : viewer.scene.canvas,
//是否贴地
// clampToGround : true
};
//从KML的URL里加载POI点位
var geocachePromise = Cesium.KmlDataSource.load('http://localhost:8080/apps/SampleData/sampleGeocacheLocations.kml',kmlOptions);
//回调
geocachePromise.then(function(dataSource){
//把所有的entities添加到viewer里显示
viewer.dataSources.add(dataSource);
//获得entity列表
var geocacheEntites = dataSource.entities.values;
for(var i = 0; i < geocacheEntites.length; i++)
{
var entity = geocacheEntites[i];
if(Cesium.defined(entity.billboard))
{
//调整垂直方向的原点,保证图标里的针尖对着地表位置
entity.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
//去掉文字的显示
entity.label = undefined;
//设置可见距离
entity.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(10.0,20000.0);
//计算经纬度(角度表示)
var cartographicPosition = Cesium.Cartographic.fromCartesian(entity.position.getValue());
var longitude = Cesium.Math.toDegrees(cartographicPosition.longitude);
var latitude = Cesium.Math.toDegrees(cartographicPosition.latitude);
}
}
});
//行政区域多边形
var geojsonOptions = {
clampToGround : true
};
//从geojson文件加载行政区多边形边界数据
var neighborhoodPromise = Cesium.GeoJsonDataSource.load('http://localhost:8080/apps/sampleData/sampleNeighborhoods.geojson',geojsonOptions);
var neighborhoods;
neighborhoodPromise.then(function(dataSource){
viewer.dataSources.add(dataSource);
neighborhoods = dataSource.entities;
//获取enty列表遍历
var neighthoodEntities = dataSource.entities.values;
for(var i = 0; i < neighthoodEntities.length; i++)
{
var entity = neighthoodEntities[i];
if(Cesium.defined(entity.polygon))
{
//设置样式代码
entity.name = entity.properties.neighborhood;
//设置一个随机半透明颜色
entity.polygon.material = Cesium.Color.fromRandom({
red : 0.1,
maximumGreen : 0.5,
minimumBlue : 0.5,
alpha : 0.6
});
//设置让多边形贴地
entity.polygon.heightReference = Cesium.heightReference.CLAMP_TO_GROUND;
//获取多边形的positions列表,并计算它的中心点
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 : true,
scale : 0.6,
horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
verticalOrigin : Cesium.VerticalOrigin.BOTTOM,
distanceDisplayCondition : new Cesium.DistanceDisplayCondition(10.0, 8000.0),
disableDepthTestDistance : 100.0
};
}
}
});
//从CZML中载入无人机轨迹
var dronePromise = Cesium.CzmlDataSource.load('http://localhost:8080/apps/sampleData/sampleFlight.czml');
var drone;
dronePromise.then(function(dataSource){
viewer.dataSources.add(dataSource);
//使用id获取在CZML数据中定义的无人机entity
drone = dataSource.entities.getById('Aircraft/Aircraft1');
//附加一些三维模型
drone.model = {
uri : 'http://localhost:8080/apps/sampleData/models/CesiumDrone.gltf',
minimumPixelSize : 128,
maximumScale : 1000,
silhouetteColor : Cesium.Color.WHITE,
silhouetteSize : 2
};
//基于无人机轨迹的位置点,自动计算朝向
drone.orientation = new Cesium.VelocityOrientationProperty(drone.position);
//光滑的飞行路径
drone.position.setInterpolationOptions({
interpolationDegree : 3,
interpolationAlgorithm : Cesium.HermitePolynomialApproximation
});
//跟踪无人机
//viewer.trackedEntity = drone;
//取消跟踪无人机
// viewer.trackedEntity = undefined;
// viewer.scene.camera.flyTo(homeCameraView);
});
//加载3dtiles建筑物模型
var tileset =viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
url : 'http://localhost:8080/apps/sampleData/Cesium3DTiles/Tilesets/Tileset/tileset.json'
//url : Cesium.IonResource.fromAssetId(3839)
}));
var defaultStyle = new Cesium.Cesium3DTileStyle({
color : 'rgba(255,255,255,0.5)',
show : true
});
tileset.style = defaultStyle;
//视点看向3dtile模型
//viewer.zoomTo(tileset);
//鼠标左键点击拾取3dtiles
var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(function(evt){
console.log(evt.position);
var feature = viewer.scene.pick(evt.position);
if(feature instanceof Cesium.Cesium3DTileFeature){
var propertyNames = feature.getPropertyNames();
var length = propertyNames.length;
for(var i = 0; i < length; i++) {
//得到ID
var propertyName = propertyNames[i];
console.log(propertyName +":"+ feature.getProperty(propertyName));
propertyName.billboard.scale = 2.0;
}
}
},
Cesium.ScreenSpaceEventType.LEFT_CLICK);
//加上entity
var wyoming = viewer.entities.add({
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]),
height : 0,
material : Cesium.Color.RED.withAlpha(0.5),
outline : true,
outlineColor : Cesium.Color.BLACK
}
});
//定位到entity
//viewer.zoomTo(wyoming);
//椭圆
var entity = viewer.entities.add({
position : Cesium.Cartesian3.fromDegrees(-103.0,40.0),
ellipse:{
semiMinorAxis : 250000.0,
semiMajorAxis : 400000.0,
//颜色材质
material : Cesium.Color.BLUE.withAlpha(0.5)
}
});
//viewer.zoomTo(viewer.entities);
var ellipse = entity.ellipse;
//图片材质
ellipse.material = 'http://localhost:8080/apps/sampleData/fire.png';
//棋盘材质
ellipse.material = new Cesium.CheckerboardMaterialProperty({
evenColor : Cesium.Color.WHITE,
oddColor : Cesium.Color.BLACK,
repeat : new Cesium.Cartesian2(4,4)
});
//条纹材质
ellipse.material = new Cesium.StripeMaterialProperty({
evenColor : Cesium.Color.WHITE,
oddColor : Cesium.Color.BLACK,
repeat : 32
});
//网格材质
ellipse.material = new Cesium.GridMaterialProperty({
color : Cesium.Color.YELLOW,
cellAlpha : 0.2,
lineCount : new Cesium.Cartesian2(8,8),
lineThickness : new Cesium.Cartesian2(2.0,2.0)
});
//黄色边线无填充,宽度2
ellipse.fill = false;
ellipse.outline = true;
ellipse.outlineColor = Cesium.Color.YELLOW;
ellipse.outlineWidth = 2.0;
//折线
var entity2 = viewer.entities.add(
{
polyline : {
positions : Cesium.Cartesian3.fromDegreesArray([ -77, 35,
-77.1,35]),
width : 5,
material : Cesium.Color.RED
}}
);
//折线边线
var polyline3 = entity2.polyline;
polyline3.material = new Cesium.PolylineOutlineMaterialProperty({
color : Cesium.Color.ORANGE,
outlineWidth : 3,
outlineColor : Cesium.Color.BLACK
});
//折线辉光
polyline3.material = new Cesium.PolylineGlowMaterialProperty({
glowPower : 0.2,
color : Cesium.Color.BLUE
});
//体块
wyoming.polygon.height = 200000;
wyoming.polygon.extrudedHeight = 250000;
//描述
wyoming.description = '\
<img\
width="50%"\
style="float:left; margin: 0 1em 1em 0;"\
src="//cesiumjs.org/tutorials/Visualizing-Spatial-Data/images/Flag_of_Wyoming.svg"/>\
<p>\
Wyoming is a state in the mountain region of the Western \
United States.\
</p>\
<p>\
Wyoming is the 10th most extensive, but the least populous \
and the second least densely populated of the 50 United \
States. The western two thirds of the state is covered mostly \
with the mountain ranges and rangelands in the foothills of \
the eastern Rocky Mountains, while the eastern third of the \
state is high elevation prairie known as the High Plains. \
Cheyenne is the capital and the most populous city in Wyoming, \
with a population estimate of 62,448 in 2013.\
</p>\
<p>\
Source: \
<a style="color: WHITE"\
target="_blank"\
href="http://en.wikipedia.org/wiki/Wyoming">Wikpedia</a>\
</p>';
var heading = Cesium.Math.toRadians(90);
var pitch = Cesium.Math.toRadians(-30);
//viewer.zoomTo(wyoming, new Cesium.HeadingPitchRange(heading, pitch));
/*
viewer.flyTo(wyoming).then(function(result){
if(result){
viewer.selectedEntity = wyoming;
}
});
*/
//wyoming.position = Cesium.Cartesian3.fromDegrees(-107.724,42.68);
//viewer.trackedEntity = wyoming;
//通知添加entity
function onChanged(collection, added, removed, changed){
var msg1 = 'added ids';
for(var i = 0; i < added.length; i++){
msg1 += '\n' + added[i].id;
}
console.log(msg1);
}
viewer.entities.collectionChanged.addEventListener(onChanged);
viewer.entities.add({
id : 'uniqueID'
});
//根据ID找对象
var theEnt = viewer.entities.getById('uniqueID');
//创建或返回
var cr = viewer.entities.getOrCreateEntity('ttt');
var e3 = new Cesium.Entity({
id : 'u3'
});
viewer.entities.add(e3);
//返回对应窗口位置所有entity列表
function drillPickEntities(viewer, windowPosition){
var pickedPrimitives = viewer.scene.drillPick(windowPosition);
var length = pickedPrimitives.length;
var result = [];
var hash = {};
for(var i = 0; i < length; i++){
var picked = pickedPrimitives[i];
var entity = Cesium.defaultValue(picked.id, picked.primitive.id);
if(entity instanceof Cesium.Entity &&
!Cesium.defined(hash[entity.id])){
result.push(entity);
hash[entity.id] = true;
}
}
}
//点和标签
var citizenBankPark = 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)
}
});
//viewer.zoomTo(citizenBankPark);
//gltf三维模型
var position_gltf = Cesium.Cartesian3.fromDegrees(-123,44,0);
var heading_gltf = Cesium.Math.toRadians(45.0);
var pitch_gltf = Cesium.Math.toRadians(15.0);
var roll_gltf = Cesium.Math.toRadians(0.0);
var orientation_gltf = Cesium.Transforms.headingPitchRollQuaternion(position_gltf, new Cesium.HeadingPitchRoll(heading_gltf,pitch_gltf,roll_gltf));
var model_gltf = viewer.entities.add({
position : position_gltf,
orientation : orientation_gltf,
model : {
uri : 'http://localhost:8080/apps/sampleData/models/GroundVehicle/GroundVehicle.glb'
}
});
viewer.trackedEntity = model_gltf;
//属性
console.log(typeof wyoming.polygon.outline);
console.log(wyoming.polygon.outline.getValue(viewer.clock.currentTime));
//返回对应窗口位置所有entity列表
function drillPickEntities(viewer, windowPosition){
var pickedPrimitives = viewer.scene.drillPick(windowPosition);
var length = pickedPrimitives.length;
var result = [];
var hash = {};
for(var i = 0; i < length; i++){
var picked = pickedPrimitives[i];
var entity = Cesium.defaultValue(picked.id, picked.primitive.id);
if(entity instanceof Cesium.Entity &&
!Cesium.defined(hash[entity.id])){
result.push(entity);
hash[entity.id] = true;
}
}
}
//点和标签
var citizenBankPark = 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)
}
});
//viewer.zoomTo(citizenBankPark);
//gltf三维模型
var position_gltf = Cesium.Cartesian3.fromDegrees(-123,44,0);
var heading_gltf = Cesium.Math.toRadians(45.0);
var pitch_gltf = Cesium.Math.toRadians(15.0);
var roll_gltf = Cesium.Math.toRadians(0.0);
var orientation_gltf = Cesium.Transforms.headingPitchRollQuaternion(position_gltf, new Cesium.HeadingPitchRoll(heading_gltf,pitch_gltf,roll_gltf));
var model_gltf = viewer.entities.add({
position : position_gltf,
orientation : orientation_gltf,
model : {
uri : 'http://localhost:8080/apps/sampleData/models/GroundVehicle/GroundVehicle.glb'
}
});
//viewer.trackedEntity = model_gltf;
//属性
console.log(typeof wyoming.polygon.outline);
console.log(wyoming.polygon.outline.getValue(viewer.clock.currentTime));
/*
//自定义相机的鼠标、键盘事件
//禁用默认的相机事件
var thgScene = viewer.scene;
var ellipsoid = viewer.scene.globe.ellipsoid;
//禁用默认相机控制事件
thgScene.screenSpaceCameraController.enableRotate = false;
thgScene.screenSpaceCameraController.enableTranslate = false;
thgScene.screenSpaceCameraController.enableZoom = false;
thgScene.screenSpaceCameraController.enableTilt = false;
thgScene.screenSpaceCameraController.enableLook = false;
//
var startMousePosition;
var mousePosition;
var flags = {
looking : false,
moveForward : false,
moveBackward : false,
moveUp : false,
moveDown : false,
moveLeft : false,
moveRight : false
};
//增加一个事件处理器,当鼠标左键点击时,存储当前相机位置,并且设置looking状态
var theHandler = new Cesium.ScreenSpaceEventHandler(theCanvas);
theHandler.setInputAction(function(movement){
flags.looking = true;
mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position);
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
theHandler.setInputAction(function(movement){
if(flags.looking){
mousePosition = movement.endPosition;
console.log(mousePosition);
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
theHandler.setInputAction(function(movement){
flags.looking = false;
console.log(mousePosition);
}, Cesium.ScreenSpaceEventType.LEFT_UP);
*/
var theCanvas = viewer.canvas;
theCanvas.setAttribute('tabindex', '0');
theCanvas.focus();
var startMousePosition;
var mousePosition;
var flags = {
looking : false,
moveForward : false,
moveBackward : false,
moveUp : false,
moveDown : false,
moveLeft : false,
moveRight : false
};
//增加一个事件处理器,当鼠标左键点击时,存储当前相机位置,并且设置looking状态
var theHandler = new Cesium.ScreenSpaceEventHandler(theCanvas);
theHandler.setInputAction(function(movement){
flags.looking = true;
mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position);
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
theHandler.setInputAction(function(movement){
if(flags.looking){
mousePosition = movement.endPosition;
console.log(mousePosition);
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
theHandler.setInputAction(function(movement){
flags.looking = false;
console.log(mousePosition);
}, Cesium.ScreenSpaceEventType.LEFT_UP);
//键盘事件
function getFlagForKeyCode(keyCode){
switch(keyCode){
case 'W'.charCodeAt(0):
return 'moveForward';
case 'S'.charCodeAt(0):
return 'moveBackward';
case 'Q'.charCodeAt(0):
return 'moveUp';
case 'E'.charCodeAt(0):
return 'moveDown';
case 'D'.charCodeAt(0):
return 'moveRight';
case 'A'.charCodeAt(0):
return 'moveLeft';
default:
return undefined;
}
}
document.addEventListener('keydown', function(e){
var flagName = getFlagForKeyCode(e.keyCode);
if(typeof flagName !== 'undefined'){
flags[flagName] = true;
console.log(flagName);
}
}, false);
document.addEventListener('keyup', function(e){
var flagName = getFlagForKeyCode(e.keyCode);
if(typeof flagName !== 'undefined'){
flags[flagName] = false;
console.log(flagName);
}
}, false);
//更新相机的位置
viewer.clock.onTick.addEventListener(function(clock){
var camera = viewer.camera;
if(flags.looking){
var width = theCanvas.clientWidth;
var height = theCanvas.clientHeight;
//鼠标点击时,这个坐标算得到0,0
var x = (mousePosition.x - startMousePosition.x) / width;
var y = -(mousePosition.y - startMousePosition.y) / height;
var lookFactor = 0.05;
camera.lookRight(x * lookFactor);
camera.lookUp(y * lookFactor);
}
//依据相机所在的绝对高度来决定相机的运行速度
var ellipsoid = viewer.scene.globe.ellipsoid;
var cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height;
var moveRate = cameraHeight / 100.0;
if( flags.moveForward){
camera.moveForward(moveRate);
}
if( flags.moveBackward){
camera.moveBackward(moveRate);
}
if( flags.moveUp ){
camera.moveUp( moveRate );
}
if( flags.moveDown){
camera.moveDown(moveRate);
}
if( flags.moveLeft){
camera.moveLeft(moveRate);
}
if( flags.moveRight) {
camera.moveRight(moveRate);
}
});
//加载汽车模型
/*
var modelMatrix_car = Cesium.Transforms.eastNorthUpToFixedFrame( Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414,0.0));
var model_car = viewer.scene.primitives.add(
Cesium.Model.fromGltf({
url : 'http://localhost:8080/apps/sampleData/models/GroundVehicle/GroundVehicle.glb',
modelMatrix : modelMatrix_car,
scale : 200.0
}));
//显示坐标系统
viewer.extend(Cesium.viewerCesiumInspectorMixin);
*/
//加载动画模型
var modelMatrix_man = Cesium.Transforms.eastNorthUpToFixedFrame( Cesium.Cartesian3.fromDegrees(-75.62898254394531, 40.02804946899414,0.0));
var model_man = viewer.scene.primitives.add(
Cesium.Model.fromGltf({
url : 'http://localhost:8080/apps/sampleData/models/CesiumMan/Cesium_Man.glb',
modelMatrix : modelMatrix_man,
scale : 200.0
}));
Cesium.when(model_man.readyPromise).then(function(model){
model.activeAnimations.addAll({
loop : Cesium.ModelAnimationLoop.REPEAT,
speedup : 0.5,
reverse : true
});
});
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. .QT-UwdXK6VZyYMhtznEEIru0AEQEzMPxDlxQw96mTlA';
var viewer = new Cesium.Viewer('cesiumContainer');
//鹰眼方式1
var viewer1 = new Cesium.Viewer('eye', {});
//设置鹰眼图属性
var control = viewer1.scene.screenSpaceCameraController;
control.enableRotate = false;
control.enableTranslate = false;
control.enableZoom = false;
control.enableTilt = false;
control.enableLook = false;
var syncViewer = function () {
viewer1.camera.flyTo({
destination: viewer.camera.position,
orientation: {
heading: viewer.camera.heading,
pitch: viewer.camera.pitch,
roll: viewer.camera.roll
},
duration: 0.0
});
};
//同步鹰眼
//viewer.scene.preRender.addEventListener(syncViewer);
//鹰眼方式2
viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(0, 0),
label: {
text: new Cesium.CallbackProperty(function () {
syncViewer();
return "";
}, true)
}
});
var viewer = new Cesium.Viewer('cesiumContainer', {
geocoder: false,
homeButton: false,
sceneModePicker: false,
baseLayerPicker: false,
navigationHelpButton: false,
animation: false,
timeline: false,
fullscreenButton: false,
vrButton: false,
//Cesium本地服务
//imageryProvider : Cesium.createTileMapServiceImageryProvider({
// url : Cesium.buildModuleUrl('http://Build/Cesium/Assets/Textures/NaturalEarthII') //
})
// });
//显示帧速
viewer.scene.debugShowFramesPerSecond = true;
//关闭大气层显示 //viewer.scene.skyAtmosphere.show = false;
//控制视角不转到地下 viewer.scene.globe.depthTestAgainstTerrain = true;
var thePosition = Cesium.Cartesian3.fromDegrees(-107.0, 40.0, 300000.0);
//方向 var theHeading = Cesium.Math.toRadians(20.0);
//倾斜角度 var thePitch = Cesium.Math.toRadians(-90.0);
var theRoll = 0;
var redBox = viewer.entities.add({
name: 'red box with black outline',
position: thePosition,
box: {
dimensions: new Cesium.Cartesian3(400000.0, 300000.0, 500000.0),
material: Cesium.Color.RED.withAlpha(0.5),
outline: true,
outlineColor: Cesium.Color.BLACK
}
});
//viewer.zoomTo(viewer.entities);
var translation = Cesium.Cartesian3.fromArray([]);
//加载3dtiles建筑物模型
var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
//数据路径
url: 'http://localhost:8080/apps/sampleData/Cesium3DTiles/Tilesets/Tileset/tileset.json',
//最大的屏幕空间误差
maximumScreenSpaceError: 2,
//最大加载瓦片个数
maximumNumberOfLoadedTiles: 1000
}));
var m = tileset.modelMatrix;
// 旋转x角度,转为弧度再参与运算
var RotateX = 90.0;
var m1 = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(RotateX));
//矩阵计算
Cesium.Matrix4.multiplyByMatrix3(m, m1, m);
//赋值
tileset.modelMatrix = m;
var defaultStyle = new Cesium.Cesium3DTileStyle({
color: 'rgba(255,255,255,0.5)',
show: true
});
tileset.style = defaultStyle; //视点看向3dtile模型 //viewer.zoomTo(tileset);
//Cartesian3方式计算视角
viewer.camera.setView({
destination: thePosition,
orientation: {
heading: theHeading,
pitch: thePitch,
roll: theRoll
}
});
//rectangle方式计算视角
viewer.camera.setView({
//西南东北
destination: Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0),
orientation: {
heading: theHeading,
pitch: thePitch,
roll: theRoll
}
});
//flyto改变视角
viewer.camera.flyTo({
destination: thePosition,
orientation: {
heading: theHeading,
pitch: thePitch,
roll: theRoll
},
//设置飞行持续时间,默认会根据距离来计算
duration: 5,
//到达位置后执行的回调函数
complete: function () {},
//如果取消飞行则会调用此函数
cancle: function () {},
//如果摄像机飞越高于该值,则调整俯仰角度,
pitchAdjustHeight: -90,
//相机最大飞行高度 maximumHeight : 5000,
//如果到达目的地有两种方式,设置具体值后会强制选择方向飞过这个经度 flyOverLongitude : 100
});
//lookAt方式控制 //
var theRange = 5000.0;
//
viewer.camera.lookAt(thePosition, new Cesium.HeadingPitchRange(theHeading, thePitch, theRange));
//加载topojson
viewer.dataSources.add(Cesium.GeoJsonDataSource.load('http://localhost:8080/apps/sampleData/ne_10m_us_states.topojson', {
stroke: Cesium.Color.HOTPINK,
fill: Cesium.Color.PINK.withAlpha(0.5),
strokeWidth: 3
}));
//纹理图绘制
function getColorRamp(elevationRamp) {
var ramp = document.createElement('canvas');
ramp.width = 1;
ramp.height = 100;
var ctx = ramp.getContext('2d');
var values = elevationRamp;
var grd = ctx.createLinearGradient(0, 0, 0, 100);
grd.addColorStop(values[0], '#000000');
//黑色 grd.addColorStop(values[1], '#2747E0');
//蓝色 grd.addColorStop(values[2], '#D33B7D');
//粉色 grd.addColorStop(values[3], '#D33038');
//红色 grd.addColorStop(values[4], '#FF9742');
//橘色 grd.addColorStop(values[5], '#ffd700');
//黄色 grd.addColorStop(values[6], '#ffffff');
//白色 ctx.fillStyle = grd; ctx.fillRect(0, 0, 1000, 10000); return ramp;
}
//渐变纹理填充墙
var redWall = viewer.entities.add({
name: 'Red wall at height',
wall: {
positions: Cesium.Cartesian3.fromDegreesArrayHeights([121.444409, 31.247417, 200.0, 121.533521, 31.235685, 200.0, 121.563273, 31.190347, 200.0, 121.546744, 31.194054, 200.0, 121.516705, 31.191459, 200.0, 121.502188, 31.203074, 200.0]),
minimumHeights: [3000.0, 2000.0, 2000, 2000, 2000, 3000],
material: getColorRamp([0.0, 0.045, 0.1, 0.15, 0.37, 0.54, 1.0], true)
}
});
//viewer.zoomTo(redWall);
//贴地线
var yellowLine = viewer.entities.add({
name: 'Red line on the surface',
corridor: {
positions: Cesium.Cartesian3.fromDegreesArray([112.82436, 23.071506, 112.82742, 23.067512, 112.828878, 23.064659, 112.830799, 23.060947, 112.832166, 24.058329]),
width: 200,
material: Cesium.Color.YELLOW
}
});
viewer.zoomTo(yellowLine);
var rectanglePrimitive = viewer.scene.primitives.add(
new Cesium.GroundPrimitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.CorridorGeometry({
vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
positions: Cesium.Cartesian3.fromDegreesArray([112.82436, 23.071506, 112.82742, 23.067512, 112.828878, 23.064659, 112.830799, 23.060947, 112.832166, 24.058329]),
width: 40000
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(0.0, 1.0, 0.0, 0.5))
}
}),
classificationType: Cesium.ClassificationType.TERRAIN
})
)
### use sampledPositionProperties
mounted() {
const viewer = new window.Cesium.Viewer("cesiumContainer", {
// 地图提供商
terrainProvider: window.Cesium.createWorldTerrain(),
});
// Cesium.createOsmBuildings()用于创建OSM建筑物图层,并加入场景
viewer.scene.primitives.add(window.Cesium.createOsmBuildings());
// 飞行轨迹点
const flightData = JSON.parse(
'[{"longitude":-122.39053,"latitude":37.61779,"height":-27.32},{"longitude":-122.39035,"latitude":37.61803,"height":-27.32},{"longitude":-122.39019,"latitude":37.61826,"height":-27.32}]'
);
const timeStepInSeconds = 30;
const totalSeconds = timeStepInSeconds * (flightData.length - 1);
// Cesium.JulianDate.fromIso8601()方法会将ISO 8601格式的时间字符串转换为一个Julian日期对象
// 该对象包含了该时间的绝对时间值,即距离儒略日(Julian Day)的秒数
const start = window.Cesium.JulianDate.fromIso8601("2020-03-09T23:10:00Z");
// Cesium.JulianDate.addSeconds是Cesium.js中用于在Julian日期对象上添加秒数的方法
const stop = window.Cesium.JulianDate.addSeconds(
start,
totalSeconds,
new window.Cesium.JulianDate()
);
// 设置开始,结束,当前时间
viewer.clock.startTime = start.clone();
viewer.clock.stopTime = stop.clone();
viewer.clock.currentTime = start.clone();
// 时间轴缩放
viewer.timeline.zoomTo(start, stop);
// 时间倍数
viewer.clock.multiplier = 50;
// 开启动画
viewer.clock.shouldAnimate = true;
// 创建一个随时间变化的位置属性
const positionProperty = new window.Cesium.SampledPositionProperty();
// 遍历坐标数组
for (let i = 0; i < flightData.length; i++) {
const dataPoint = flightData[i];
// 坐标的时间
const time = window.Cesium.JulianDate.addSeconds(
start,
i * timeStepInSeconds,
new window.Cesium.JulianDate()
);
// 坐标的地点
const position = window.Cesium.Cartesian3.fromDegrees(
dataPoint.longitude,
dataPoint.latitude,
dataPoint.height
);
// 新增采样
positionProperty.addSample(time, position);
// 新增实例,点击可查看描述信息
viewer.entities.add({
description: `Location: (${dataPoint.longitude}, ${dataPoint.latitude}, ${dataPoint.height})`,
position: position,
point: { pixelSize: 10, color: window.Cesium.Color.RED },
});
}
// 追踪
viewer.trackedEntity = viewer.entities.add({
// TimeIntervalCollection中包含了多个TimeInterval对象,每个TimeInterval对象描述了一个时间段。
// TimeInterval对象包含了起始时间和结束时间以及一些额外的属性
availability: new window.Cesium.TimeIntervalCollection([
new window.Cesium.TimeInterval({ start: 3, stop: stop }),
]),
position: positionProperty,
point: { pixelSize: 30, color: window.Cesium.Color.GREEN },
// 路径图形
path: new window.Cesium.PathGraphics({ width: 3 }),
});
},