Cesium Basic Tutorial

I. Overview

Cesium is a foreign javascript-based map engine that supports 3D, 2D, and 2.5D forms of display. It can draw graphics and highlight areas by itself, and provides good touch support, and supports most browsers and mobile terminals.

  • Cesium is a cross-platform, cross-browser javascript library for displaying 3D globes and maps.
  • Cesium uses WebGL for hardware-accelerated graphics and does not require any plug-in support, but the browser must support WebGL.
  • Cesium is an open source program licensed under Apache 2.0. It is free for commercial and non-commercial use.

2. Installation

The current case is based on vue3+vitebuilding

1. Install the plugin

Plug-in address

npm i cesium vite-plugin-cesium vite -D
# yarn add cesium vite-plugin-cesium vite -D

2. Configuration

vite.config.jsConfiguration:

import {
    
     defineConfig } from 'vite';
import cesium from 'vite-plugin-cesium';
export default defineConfig({
    
    
  plugins: [cesium()]
});

3. Create a Viewer

1. Basic Viewer

<template>
    <div id="cesiumContainer"></div>
</template>

<script lang="ts" setup>
import {
    
     onMounted } from "vue";
import {
    
     Viewer } from 'cesium';
onMounted(() => {
    
    
    const viewer = new Viewer('cesiumContainer');
})
</script>
<style lang="scss" scoped></style>

2. Auxiliary button

insert image description here

  1. Geocoder : A geolocation search tool that displays the geographic location visited by the camera. By default, Microsoft's Bing Maps are used.
  2. HomeButton : Home button, click to switch the view to the default view.
  3. SceneModePicker : Toggle between 2D, 3D and Columbus View (CV) modes.
  4. BaseLayerPicker : Select the base map (imagery and terrain) of the 3D Digital Earth.
  5. NavigationHelpButton : Help tips, how to operate Digital Earth.
  6. Animation : Control the playback speed of the window animation.
  7. CreditsDisplay : Displays trademark credits and data sources.
  8. Timeline : Displays the current time and allows the user to drag the progress bar to any specified time.
  9. FullscreenButton : Inspect the fullscreen button.

4. Cesium Ion

In the process of using Cesium, if we do not apply for ion and do not have the data source provided by cesium for our own data source, a line of small English letters will often be prompted at the bottom of the viewer. It means that an application is required access token.
insert image description here

  1. First you need to register a free Cesium ion account.
  2. Open Cesium ion and register a new account.
  3. Click "Access Token" to jump to Access Tokens pagethe page.
  4. Select Default and copy the default access token to contents.
    insert image description here
    When creating Cesium Viewer, access tokenjust fill in your own access token.
Cesium.Ion.defaultAccessToken = '<YOUR ACCESS TOKEN HERE>';

At this point the small print at the bottom disappears!
The above can easily access various data sources provided by Cesium ion.

5. Add layers

Another key element of a Cesium application is the Imagery (layer). The collection of tile maps is mapped to the surface of the virtual three-dimensional digital earth according to different projection methods. Depending on the direction and distance from the camera to the surface, Cesium will request and render different levels of layer detail.
Various layers can be added, removed, sorted and adapted to Cesium.

Cesium provides a series of methods for processing layers, such as color adaptation, layer overlay fusion. Some sample code is as follows:

Cesium provides various interfaces to support various layer data sources.

Supported Layer Formats

  • wms
  • TMS
  • WMTS (with time dynamic imagery)
  • ArcGIS
  • Bing Maps
  • Google Earth
  • Mapbox
  • OpenStreetMap

Note: Different data sources require different authentication - you need to ensure that you have permission to access these data sources, and naturally you need to register specific authentication to do so. By default,
Cesium uses Bing Mapsas the default layer. This layer is packaged into Viewer for presentation. Cesium requires you to create an ion account and generate an access key to access layer data.

  1. Go to Cesium ionthe page and add the Sentinel-2 layer to your own assets. Click " Asset Depot" in the navigation bar
    insert image description here

  2. Click Add to my assets . Sentinel-2 will appear in the asset list (My Assets) in your personal user, and the layer data source will become available in the personal app at this time.

  3. Code modification
    We create one IonImageryProviderand pass the assetId to the corresponding Sentinel-2layer. Then we'll ImageryProvideradd to the viewer.imageryLayers.

// Remove default base layer
viewer.imageryLayers.remove(viewer.imageryLayers.get(0));

// Add Sentinel-2 imagery
viewer.imageryLayers.addImageryProvider(new Cesium.IonImageryProvider({
    
     assetId : 3954 }));

Sentinel-2: cloud-free satellite imagery of the world down to 10-meter resolution

insert image description here

6. Add terrain

Cesium supports streamlined, visualized global elevation projection terrain and water shape data, including oceans, lakes, rivers, mountains, canyons, and other terrain data that can be displayed in three dimensions and are better than two-dimensional. Like layer data, the Cesium engine requests streamed terrain data from a server, requesting only those layers that need to be drawn based on what the current camera can see.

Cesium officially provides some examples of terrain datasets and how to configure these parameters.

Supported terrain data formats:

  • Quantized-mesh, a format open sourced by the Cesium team
  • Heightmap
  • Google Earth Enterprise

In order to add terrain data, we need to create one CesiumTerrainProvider, provide a url and some configuration items, and then assign this provider to viewer.terrainProvider.

Here we use Cesium WorldTerrianlayers, provided by , which Cesium ionare provided by default in My Assets. We can use createWorldTerrainhelperfunctions to create a Cesium WorldTerrian served by Cesium ion.

// Load Cesium World Terrain
viewer.terrainProvider = Cesium.createWorldTerrain({
    
    
    requestWaterMask : true, // required for water effects
    requestVertexNormals : true // required for terrain lighting
});

*requestWaterMaskand requestVertexNormalsare optional configuration items that tell Cesium whether to request additional water and light data. These two options are set to false by default. *

Ultimately, now that we have the terrain data, we need more lines to make the objects behind the terrain data appear correctly, only the frontmost, topmost objects are visible.

// Enable depth testing so things behind the terrain disappear.
viewer.scene.globe.depthTestAgainstTerrain = true;

We now have terrain data and moving water. New York is very flat, so it can be freely explored on the terrain data above. As an obvious example, you can jump to more rugged areas like Grand Canyon or San Francisco.
insert image description here

7. Configuration window

Next we will add some more correct time and space settings to the Viewer. Involves interacting with viewer.scene, which controls all graphical elements in the viewer.

  1. First, let's configure our scene to activate lighting based on the sun's position with the following code:
// Enable lighting based on sun/moon positions
viewer.scene.globe.enableLighting = true;

According to the above configuration, the lighting in our scene (scene) will change with the time of day. If you zoom out, you will see part of the digital earth in the dark, because to simulate the real earth, the sun can only illuminate part of the earth.

  1. Before we start initializing the startup view, let's briefly go over some basic Cesium types:
    Cartesian3 : A 3D Cartesian coordinate - when used as a position relative to the center of the Earth, using the Earth Fixed Frame (ECEF).
    Cartographic : A position determined by longitude, latitude (radians), and height of the WGS84 ellipsoid.
    HeadingPitchRoll : Rotation (in radians) about the local axis in a north-east-up frame. Heading is the rotation around the negative Z axis. Pitch is the rotation around the negative Y axis. Roll is the rotation about the positive X axis.
    Quaternion : 3D rotation expressed in 4D coordinates.

These are the basic types necessary to position and position Cesium objects in the scene, and have a number of useful conversion methods. See the documentation for each type for more information.
Now let's position the camera in the NYC (New York) scene where our data resides.

1、Camera Control

Camera is viewer.scenea property in , used to control the currently visible field. We can control the camera by directly setting its position and orientation, or by using the API provided by Cesium, which is designed to specify the change of the camera's position and orientation over time.

Some of the most commonly used methods are as follows:
Camera.setView(options) : Instantly sets the camera at a specific position and orientation.
Camera.zoomIn(amount) : Move the camera along the view vector.
Camera.zoomOut(amount) : Move the camera backwards along the view vector.
Camera.flyTo(options) : Creates an animated camera fly from the current camera position to the new position.
Camera.lookAt(target, offset) : Locate and position the camera to aim at the target point by the given offset.
Camera.move(direction, amount) : Move the camera in any direction.
Camera.rotate(axis, angle) : Rotate the camera around an arbitrary axis.

To get further into the API capabilities, check out these camera demos:
Camera API Demo
Custom Camera Controls Demo

Let's try a way to jump the camera to New York. Use camera.setView()the initialized view to specify the camera's position and orientation using Cartesian3 and HeadingpitchRoll:

// Create an initial camera view
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
    }
};
// Set the initial view
viewer.scene.camera.setView(homeCameraView);

The camera is now positioned and oriented to look down on Manhattan, and our view parameters are saved in an object that we can pass to other camera methods.
The effect is as follows:
Please add a picture description
In fact, we can use this same perspective to update the effect of pressing the home button. Instead of having it return the default view of Earth from a distance, we can override the button so that we see the initial view of Manhattan. We can tweak the animation by adding a few options, then add an event listener that cancels the default flight, and calls FlyTo()our Home view:

// Add some camera flight animation options
homeCameraView.duration = 2.0;
homeCameraView.maximumHeight = 2000;
homeCameraView.pitchAdjustHeight = 2000;
homeCameraView.endTransform = Cesium.Matrix4.IDENTITY;
// Override the default home button
viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function (e) {
    
    
    e.cancel = true;
    viewer.scene.camera.flyTo(homeCameraView);
});

After clicking the Home button, the view will jump directly to the sky over New York
insert image description here

For more on basic camera controls, visit our Camera Tutorial .

2、Clock Control

Next, we configure the Clock and Timline of the viewer to control the time progress of the scene.

Here is the related API of clock

When using specific times, Cesium uses the JulandDATE type, which stores the number of days since noon on January 1 - 4712 (4713 BC). To improve precision, this class stores the full part of the date and seconds in separate components. For calculation safety and to represent leap seconds, dates are always stored in the International Atomic Time Standard.

Here is an example of how we can set the scene timing options:

// Set up clock and timeline.
viewer.clock.shouldAnimate = true; // make the animation play when the viewer starts
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; // sets a speedup
viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER; // tick computation mode
viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; // loop at the end
viewer.timeline.zoomTo(viewer.clock.startTime, viewer.clock.stopTime); // set visible range

This sets the rate, start and stop times for the scene animation, and tells the clock to cycle back to the start when the stop time is reached. It also sets the timeline controls to the appropriate time range. Check out this clock sample code to test clock settings.

Here is our initial scene configuration! Now, when you run your application, you should see the following:
The effect is as follows:
Please add a picture description

8. Loading and styling entities

The entity uses the entity provided by the Cesium official website: kml download address

    var options = {
    
    
        camera: viewer.scene.camera,
        canvas: viewer.scene.canvas,
        screenOverlayContainer: viewer.container,
    };

    var dataSourcePromise= Cesium.KmlDataSource.load('/cesium/gdpPerCapita2008.kmz', options);
    // viewer.dataSources.add(dataSourcePromise); 可以选择一次性加载
    dataSourcePromise.then(dataSource => {
    
    
        viewer.dataSources.add(dataSource);

        var geocacheEntities = dataSource.entities.values;
        for (var i = 0; i < geocacheEntities.length; i++) {
    
    
            var entity = geocacheEntities[i];
            if (Cesium.defined(entity.billboard)) {
    
    
                // 这里可以篡改entity的样式
            }
        }
    })
    viewer.camera.flyHome(0);

The effect is as follows:
insert image description here
Entity structure is as follows:
insert image description here

hot key

  • Hold down the left mouse button and drag - pans the camera on the digital earth plane.
  • Hold down the right mouse button and drag - zoom camera.
  • Mouse wheel swipe - zoom camera.
  • Middle mouse button drag - Rotate the camera at the current mid-screen point of the globe.

[Quoting Tutorial]
Chinese Tutorial for Beginners

Guess you like

Origin blog.csdn.net/bobo789456123/article/details/130208403