cesium官方教程笔记4,5,6

Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJjOWM3MzYxZS0xNDg5LTRhYzgtOTE3ZS1hMTgyNmFmNzY5ZDIiLCJpZCI6MTYwNTYsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1Njk0NzMxMjl9.QT-UwdXK6VZyYMhtznEEIru0AEQEzMPxDlxQw96mTlA';
//arcgis影像图层加载
var imagelayer_ArcGis = new Cesium.ArcGisMapServerImageryProvider({
    url : 'http://services.arcgisonline.com/ArcGIS/rest/services/world_imagery/mapserver'
    });
var viewer = new Cesium.Viewer('cesiumContainer',{
    terrainProvider : Cesium.createWorldTerrain({
        requestWaterMask : true,
        requestVertexNormals : true
    }),
    
    imageryProvider : imagelayer_ArcGis,
    scene3DOnly : true,
    //selectionIndicator : false,
    baseLayerPicker : false
});
//添加NASA BLACK Marble影像(使用TMS)
var imageLayers = viewer.scene.imageryLayers;
var blackMarble = imageLayers.addImageryProvider( new Cesium.createTileMapServiceImageryProvider({
    url : 'http://cesiumjs.org/tilesets/imagery/blackmarble',
    maximumLevel : 8,
    credit : 'Black Marble imagery courtesy NASA Earth Observatory',
    alpha : 0.5,
    brightness : 2.0
}));

//添加只覆盖某个范围的单一图片的图层
var singleImageLayer = new Cesium.SingleTileImageryProvider({
    url : 'http://localhost:8080/apps/Sandcastle/images/Cesium_Logo_overlay.png',
    rectangle : Cesium.Rectangle.fromDegrees(-75.0, 28.0, -67.0, 29.75)
});
imageLayers.addImageryProvider(singleImageLayer );

//打开深度测试,那么在地形以下的对象不可见
viewer.scene.globe.depthTestAgainstTerrain = true;
//开启全球光照
//viewer.scene.globe.enableLighting = true;
//创建相机初始位置和朝向
var initialPosition = new Cesium.Cartesian3.fromDegrees(-75,28,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 = '\
  width="50%"\
  style="float:left; margin: 0 1em 1em 0;"\
  src="//cesiumjs.org/tutorials/Visualizing-Spatial-Data/images/Flag_of_Wyoming.svg"/>\

\
  Wyoming is a state in the mountain region of the Western \
  United States.\

\

\
  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.\

\

\
  Source: \
      target="_blank"\
    href="http://en.wikipedia.org/wiki/Wyoming">Wikpedia
\

';

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));

/*
//自定义相机的鼠标、键盘事件
//禁用默认的相机事件
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);
    }
        
});
       
        

 

你可能感兴趣的:(cesium官方教程笔记4,5,6)