Cesium學習筆記(一)

小王也要加油哦發表於2020-11-29

Cesium

官網教程原始碼分析

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://cesiumjs.org/releases/1.75/Build/Cesium/Cesium.js"></script>
  <link href="https://cesiumjs.org/releases/1.75/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
  <link href="style.css" rel="stylesheet">
</head>
<body>
  <div id="cesiumContainer"></div>
  <script>
    // Get your token from https://cesium.com/ion/tokens
    Cesium.Ion.defaultAccessToken = 'your_token_here';

    // STEP 4 CODE (replaces steps 2 and 3)
    // Keep your `Cesium.Ion.defaultAccessToken = 'your_token_here'` line from before here. 
    const viewer = new Cesium.Viewer('cesiumContainer', {
      terrainProvider: Cesium.createWorldTerrain()
    });
    const osmBuildings = viewer.scene.primitives.add(Cesium.createOsmBuildings());

    const flightData = JSON.parse(
      '[{"longitude":-122.39053,"latitude":37.61779,"height":-27.32},{"longitude":-122.39035,"latitude":37.61803,"height":-27.32},
      //............................
      //此處省略多行座標資訊程式碼
    );

    /* Initialize the viewer clock:
      Assume the radar samples are 30 seconds apart, and calculate the entire flight duration based on that assumption.
      Get the start and stop date times of the flight, where the start is the known flight departure time (converted from PST 
        to UTC) and the stop is the start plus the calculated duration. (Note that Cesium uses Julian dates. See 
        https://simple.wikipedia.org/wiki/Julian_day.)
      Initialize the viewer's clock by setting its start and stop to the flight start and stop times we just calculated. 
      Also, set the viewer's current time to the start time and take the user to that time. 
    */
    const timeStepInSeconds = 30;
    const totalSeconds = timeStepInSeconds * (flightData.length - 1);
    const start = Cesium.JulianDate.fromIso8601("2020-03-09T23:10:00Z");
    //結束時間=開始時間加上總時間,返回一個新的JulianDate物件:
    const stop = Cesium.JulianDate.addSeconds(start, totalSeconds, new Cesium.JulianDate());
    viewer.clock.startTime = start.clone();
    viewer.clock.stopTime = stop.clone();
    viewer.clock.currentTime = start.clone();
    viewer.timeline.zoomTo(start, stop);	//viewer.zoomTo(target, offset):非同步設定攝像機來檢視實體,此處是timeline.zoomTo,不知道有何區別
    // Speed up the playback speed 50x.
    viewer.clock.multiplier = 50;
    // Start playing the scene.
    viewer.clock.shouldAnimate = true;	//開始tick。The clock will only tick when both Clock.canAnimate and Clock.shouldAnimate are true. Clock.canAnimate 預設為true

    // The SampledPositionedProperty stores the position and timestamp for each sample along the radar sample series.
    const positionProperty = new Cesium.SampledPositionProperty();

    for (let i = 0; i < flightData.length; i++) {
      const dataPoint = flightData[i];

      // Declare the time for this individual sample and store it in a new JulianDate instance.
      const time = Cesium.JulianDate.addSeconds(start, i * timeStepInSeconds, new Cesium.JulianDate());
      const position = Cesium.Cartesian3.fromDegrees(dataPoint.longitude, dataPoint.latitude, dataPoint.height);//根據經緯度座標建立一個笛卡爾座標系物件
      // Store the position along with its timestamp.
      // Here we add the positions all upfront, but these can be added at run-time as samples are received from a server.
      positionProperty.addSample(time, position);

      viewer.entities.add({
        description: `Location: (${dataPoint.longitude}, ${dataPoint.latitude}, ${dataPoint.height})`,
        position: position,
        point: { pixelSize: 10, color: Cesium.Color.RED }
      });
    }

    // STEP 6 CODE (airplane entity)
    async function loadModel() {
      // Load the glTF model from Cesium ion.
      const airplaneUri = await Cesium.IonResource.fromAssetId(your_asset_id);	//封裝資源
      const airplaneEntity = viewer.entities.add({//viewer.entities: Gets the collection of entities not tied to a particular data source. 
      
        availability: new Cesium.TimeIntervalCollection([ new Cesium.TimeInterval({ start: start, stop: stop }) ]),
        position: positionProperty,
        // Attach the 3D model instead of the green point.
        model: { uri: airplaneUri },
        // Automatically compute the orientation from the position.
        orientation: new Cesium.VelocityOrientationProperty(positionProperty),    
        path: new Cesium.PathGraphics({ width: 3 })
        
      });
      
      viewer.trackedEntity = airplaneEntity;
    }

    loadModel();
  </script>
</body>
</html>
  • viewer.clock.canAnimateviewer.clock.shouldAnimate要同時為true才會開始clock tick。canAnimate預設為true,shouldAnimate預設是false。
  • Cesium.Cartesian3:笛卡爾座標系(直角座標系),Cesium.Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid, result)根據經緯度座標建立,返回一個Cartesian3物件。
  • asyncawait
    • 將 async 關鍵字加到函式申明中,可以告訴它們返回的是 promise,而不是直接返回值。此外,它避免了同步函式為支援使用 await 帶來的任何潛在開銷。在函式宣告為 async 時,JavaScript引擎會新增必要的處理,以優化你的程式。
    • 當 await 關鍵字與非同步函式一起使用時,它的真正優勢就變得明顯了 —— 事實上, await 只在非同步函式裡面才起作用。它可以放在任何非同步的,基於 promise 的函式之前。它會暫停程式碼在該行上,直到 promise 完成,然後返回結果值。在暫停的同時,其他正在等待執行的程式碼就有機會執行了。
  • Cesium.IonResource(endpoint, endpointResource):A Resource instance that encapsulates(封裝) Cesium ion asset access. This object is normally not instantiated(例項化) directly.
  • viewer.entities:Gets the collection of entities not tied to(繫結) a particular data source.
  • new Cesium.TimeIntervalCollection(intervals):A non-overlapping collection of TimeInterval instances sorted by start time.
  • new Cesium.VelocityOrientationProperty(position, ellipsoid): A Property which evaluates to a Quaternion(四元數) rotation(旋轉) based on the velocity of the provided PositionProperty.
  • new Cesium.PathGraphics(options): Describes a polyline(多段線) defined as the path made by an Entity as it moves over time.

相關文章