### Initialize Cesium Viewer from CDN
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-quickstart
This HTML snippet demonstrates how to set up a CesiumJS application by importing the necessary JavaScript and CSS files from a CDN. It initializes the Cesium Viewer, sets a default access token, flies the camera to San Francisco, and adds the Cesium OSM Buildings layer. Replace 'your_access_token' with your actual Cesium ion access token.
```html
```
--------------------------------
### Model Loading Examples
Source: https://cesium.com/learn/cesiumjs/ref-doc/Model
Examples demonstrating how to load glTF models asynchronously, add them to the scene, and position them with modelMatrix.
```APIDOC
## Loading and Adding a Model
### Description
Loads a glTF model asynchronously and adds it to the Cesium scene.
### Method
`Cesium.Model.fromGltfAsync(options)
### Endpoint
N/A (Client-side JavaScript API)
### Parameters
#### Request Body
- **url** (string) - Required - The URL of the glTF asset.
### Request Example
```javascript
try {
const model = await Cesium.Model.fromGltfAsync({
url: "../../SampleData/models/CesiumMan/Cesium_Man.glb"
});
viewer.scene.primitives.add(model);
} catch (error) {
console.log(`Failed to load model. ${error}`);
}
```
### Response
#### Success Response (Model)
- **model** (Cesium.Model) - The loaded model object.
#### Response Example
(See Request Example - the result is implicitly used by adding to `viewer.scene.primitives`)
## Positioning a Model
### Description
Loads a glTF model and positions it using `modelMatrix`, also setting a minimum pixel size.
### Method
`Cesium.Model.fromGltfAsync(options)
### Endpoint
N/A (Client-side JavaScript API)
### Parameters
#### Request Body
- **url** (string) - Required - The URL of the glTF asset.
- **modelMatrix** (Cesium.Matrix4) - Required - The transformation matrix to position the model.
- **minimumPixelSize** (number) - Optional - The minimum size of the model in pixels.
### Request Example
```javascript
const position = Cesium.Cartesian3.fromDegrees(
-123.0744619,
44.0503706,
5000.0
);
const headingPositionRoll = new Cesium.HeadingPitchRoll();
const fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator(
"north",
"west"
);
try {
const model = await Cesium.Model.fromGltfAsync({
url: "../../SampleData/models/CesiumAir/Cesium_Air.glb",
modelMatrix: Cesium.Transforms.headingPitchRollToFixedFrame(
position,
headingPositionRoll,
Cesium.Ellipsoid.WGS84,
fixedFrameTransform
),
minimumPixelSize: 128,
});
viewer.scene.primitives.add(model);
} catch (error) {
console.log(`Failed to load model. ${error}`);
}
```
### Response
#### Success Response (Model)
- **model** (Cesium.Model) - The loaded and positioned model object.
#### Response Example
(See Request Example - the result is implicitly used by adding to `viewer.scene.primitives`)
## Model Animation Control
### Description
Loads a glTF model, retrieves its animations, and plays the last animation at half speed.
### Method
`Cesium.Model.fromGltfAsync(options)
### Endpoint
N/A (Client-side JavaScript API)
### Parameters
#### Request Body
- **url** (string) - Required - The URL of the glTF asset.
- **gltfCallback** (function) - Optional - A callback function that receives the glTF object and can be used to access animations.
### Request Example
```javascript
let animations;
try {
const model = await Cesium.Model.fromGltfAsync({
url: "../../SampleData/models/CesiumMan/Cesium_Man.glb",
gltfCallback: gltf => {
animations = gltf.animations
}
});
viewer.scene.primitives.add(model);
model.readyEvent.addEventListener(() => {
model.activeAnimations.add({
index: animations.length - 1,
loop: Cesium.ModelAnimationLoop.REPEAT,
multiplier: 0.5,
});
});
} catch (error) {
console.log(`Failed to load model. ${error}`);
}
```
### Response
#### Success Response (Model)
- **model** (Cesium.Model) - The loaded model object with animations configured.
#### Response Example
(See Request Example - the result is implicitly used by adding to `viewer.scene.primitives`)
```
--------------------------------
### Initialize Cesium Viewer with NPM
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-quickstart
This JavaScript snippet shows how to set up a CesiumJS application when using a module bundler like Webpack. It imports necessary components from the 'cesium' package, configures the base URL for static files, sets the access token, and initializes the Cesium Viewer with a fly-to animation and 3D buildings layer. Ensure 'your_access_token' is replaced with your actual Cesium ion access token.
```javascript
// The URL on your server where CesiumJS's static files are hosted.
window.CESIUM_BASE_URL = '/';
import { Cartesian3, createOsmBuildingsAsync, Ion, Math as CesiumMath, Terrain, Viewer } from 'cesium';
import "cesium/Build/Cesium/Widgets/widgets.css";
// Your access token can be found at: https://ion.cesium.com/tokens.
// Replace `your_access_token` with your Cesium ion access token.
Ion.defaultAccessToken = 'your_access_token';
// Initialize the Cesium Viewer in the HTML element with the `cesiumContainer` ID.
const viewer = new Viewer('cesiumContainer', {
terrain: Terrain.fromWorldTerrain(),
});
// Fly the camera to San Francisco at the given longitude, latitude, and height.
viewer.camera.flyTo({
destination: Cartesian3.fromDegrees(-122.4175, 37.655, 400),
orientation: {
heading: CesiumMath.toRadians(0.0),
pitch: CesiumMath.toRadians(-15.0),
}
});
// Add Cesium OSM Buildings, a global 3D buildings layer.
const buildingTileset = await createOsmBuildingsAsync();
viewer.scene.primitives.add(buildingTileset);
```
--------------------------------
### Install webpack-dev-server
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Installs the webpack-dev-server as a development dependency. This tool provides a development environment with live reloading capabilities.
```bash
npm install --save-dev webpack-dev-server
```
--------------------------------
### Install and Run CesiumJS Local Server (Node.js)
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-google-earth-api/cesiumjs-google-earth-api-part-i
Instructions to install Node.js dependencies and start the local CesiumJS server for development. This requires Node.js to be installed on the system.
```bash
npm install
node server.js
```
--------------------------------
### 3D Tiles Styling Language Example
Source: https://cesium.com/learn/cesiumjs/ref-doc/TimeDynamicPointCloud
An example demonstrating how to apply a Cesium 3D Tiles style to a point cloud.
```APIDOC
## 3D Tiles Styling Language Example
### Description
This example shows how to define a `Cesium3DTileStyle` for a point cloud, controlling its color and visibility based on classification properties.
### Code Example
```javascript
pointCloud.style = new Cesium.Cesium3DTileStyle({
color : {
conditions : [
['${Classification} === 0', 'color("purple", 0.5)'],
['${Classification} === 1', 'color("red")'],
['true', '${COLOR}']
]
},
show : '${Classification} !== 2'
});
```
### See
* 3D Tiles Styling language
```
--------------------------------
### Run npm start command
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Executes the 'start' script, launching the webpack development server. The application will be served at localhost:8080, and any changes made during development will be reflected automatically.
```bash
npm start
```
--------------------------------
### Install Webpack
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Installs webpack as a development dependency for the project. This command adds webpack to the project's build tools.
```bash
npm install --save-dev webpack
```
--------------------------------
### Define npm start script and configure devServer
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Adds a 'start' script to package.json to run the webpack development server. It also configures the 'devServer' in webpack.config.js to serve files from the 'dist' directory and includes the '--open' flag to automatically open the application in a browser.
```javascript
"scripts": {
"build": "node_modules/.bin/webpack --config webpack.config.js",
"start": "node_modules/.bin/webpack-dev-server --config webpack.config.js --open"
}
// development server options
devServer: {
contentBase: path.join(__dirname, "dist")
}
```
--------------------------------
### Install Copy Webpack Plugin
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Installs the 'copy-webpack-plugin' as a development dependency, which is used to copy CesiumJS static assets to the build directory.
```bash
npm install --save-dev copy-webpack-plugin
```
--------------------------------
### Complete CesiumJS Imagery Visualization Example
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-imagery
A comprehensive JavaScript example demonstrating the initialization of a Cesium Viewer, adding multiple imagery layers from Cesium ion, blending them using alpha and brightness, and overlaying a single image with a defined extent. This code snippet combines all the functionalities discussed in the tutorial.
```javascript
Cesium.Ion.defaultAccessToken = "your_access_token";
const viewer = new Cesium.Viewer("cesiumContainer", {
baseLayer: Cesium.ImageryLayer.fromProviderAsync(
Cesium.IonImageryProvider.fromAssetId(
3830183
)
),
baseLayerPicker: false,
});
const layers = viewer.imageryLayers
const blackMarble = Cesium.ImageryLayer.fromProviderAsync(
Cesium.IonImageryProvider.fromAssetId(3812)
);
blackMarble.alpha = 0.5; // 0.0 is transparent. 1.0 is opaque.
blackMarble.brightness = 2.0; // > 1.0 increases brightness. < 1.0 decreases.
layers.add(blackMarble);
const cesiumLogo = Cesium.ImageryLayer.fromProviderAsync(
Cesium.SingleTileImageryProvider.fromUrl(
"../images/Cesium_Logo_overlay.png",
{
rectangle: Cesium.Rectangle.fromDegrees(
-75.0, 28.0,
-67.0, 29.75
),
}
)
);
layers.add(cesiumLogo);
```
--------------------------------
### Install html-webpack-plugin
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Installs the html-webpack-plugin as a development dependency. This plugin simplifies the creation of HTML files to serve your webpack bundles.
```bash
npm install --save-dev html-webpack-plugin
```
--------------------------------
### Install Loaders for Webpack
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Installs necessary loaders for webpack to process CSS and other static assets. These include style-loader, css-loader, and url-loader.
```bash
npm install --save-dev style-loader css-loader url-loader
```
--------------------------------
### Initialize Cesium Viewer with Google Geocoder
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-photorealistic-3d-tiles
Initializes a CesiumJS Viewer, disabling default terrain and imagery, and configuring it to use the Google geocoder. This setup is crucial for integrating Google Maps Platform services.
```javascript
Cesium.Ion.defaultAccessToken = "";
const viewer = new Cesium.Viewer("cesiumContainer", {
globe: false,
geocoder: Cesium.IonGeocodeProviderType.GOOGLE,
});
```
--------------------------------
### Installing and Configuring UglifyJsPlugin for Minification
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Explains how to install and configure `uglifyjs-webpack-plugin` to minify JavaScript files and `css-loader` with the `minimize` option to minify CSS files for production builds, reducing file sizes.
```javascript
npm install uglifyjs-webpack-plugin --save-dev
```
```javascript
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
```
```javascript
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
```
```javascript
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
// minify loaded css
minimize: true
}
}
]
}]
}
```
--------------------------------
### KmlTour Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/KmlTour
Initializes a new KmlTour instance. A KmlTour guides the camera to specified destinations at given time intervals using KmlTourFlyTo and KmlTourWait entries.
```APIDOC
## new Cesium.KmlTour(name, id, playlist)
### Description
Initializes a new KmlTour instance. A KmlTour guides the camera to specified destinations at given time intervals using KmlTourFlyTo and KmlTourWait entries.
### Parameters
#### Path Parameters
* **name** (string) - Required - name parsed from KML
* **id** (string) - Required - id parsed from KML
* **playlist** (Array) - Required - array with KmlTourFlyTos and KmlTourWaits
### See:
* KmlTourFlyTo
* KmlTourWait
### Demo:
* KML Tours
```
--------------------------------
### Install CesiumJS Module
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Installs the CesiumJS module from npm and adds it as a development dependency to your project's package.json file.
```bash
npm install --save-dev cesium
```
--------------------------------
### Example: Edge Detection and Silhouette Stages
Source: https://cesium.com/learn/cesiumjs/ref-doc/PostProcessStageLibrary
Demonstrates how to create and use edge detection stages with custom colors and apply them to specific features, combined with a silhouette stage for visual emphasis.
```javascript
// multiple silhouette effects
const yellowEdge = Cesium.PostProcessStageLibrary.createEdgeDetectionStage();
yellowEdge.uniforms.color = Cesium.Color.YELLOW;
yellowEdge.selected = [feature0];
const greenEdge = Cesium.PostProcessStageLibrary.createEdgeDetectionStage();
greenEdge.uniforms.color = Cesium.Color.LIME;
greenEdge.selected = [feature1];
// draw edges around feature0 and feature1
postProcessStages.add(Cesium.PostProcessStageLibrary.createSilhouetteStage([yellowEdge, greenEdge]));
```
--------------------------------
### I3SDataProvider Constructor Options Example
Source: https://cesium.com/learn/cesiumjs/ref-doc/I3SDataProvider
Demonstrates how to initialize an I3SDataProvider with custom Cesium3DTileset options, such as adjusting the maximum screen space error for Level of Detail (LOD) or setting a custom outline color.
```javascript
// Example 1: Increase LOD by reducing SSE
const cesium3dTilesetOptions1 = {
maximumScreenSpaceError: 1,
};
const i3sOptions1 = {
cesium3dTilesetOptions: cesium3dTilesetOptions1,
};
// Example 2: Set a custom outline color
const cesium3dTilesetOptions2 = {
outlineColor: Cesium.Color.BLUE,
};
const i3sOptions2 = {
cesium3dTilesetOptions: cesium3dTilesetOptions2,
applySymbology: true,
};
// const i3sDataProvider = new Cesium.I3SDataProvider(i3sOptions1);
// const i3sDataProvider2 = new Cesium.I3SDataProvider(i3sOptions2);
```
--------------------------------
### Billboard Properties
Source: https://cesium.com/learn/cesiumjs/ref-doc/Billboard
This section details the various properties of a Cesium Billboard object, including how to set and get them, along with usage examples.
```APIDOC
## Billboard Properties
### Description
Provides access to the properties of a Billboard object, which represents a viewport-aligned image positioned in the 3D scene.
### Method
N/A (Properties are accessed directly on a Billboard instance)
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
## Properties
### `alignedAxis`
- **Type**: `Cartesian3`
- **Description**: Gets or sets the aligned axis in world space. The aligned axis is the unit vector that the billboard up vector points towards. The default is the zero vector, which means the billboard is aligned to the screen up vector.
- **Examples**:
```javascript
// Example 1. Have the billboard up vector point north
billboard.alignedAxis = Cesium.Cartesian3.UNIT_Z;
```
```javascript
// Example 2. Have the billboard point east.
billboard.alignedAxis = Cesium.Cartesian3.UNIT_Z;
billboard.rotation = -Cesium.Math.PI_OVER_TWO;
```
```javascript
// Example 3. Reset the aligned axis
billboard.alignedAxis = Cesium.Cartesian3.ZERO;
```
### `color`
- **Type**: `Color`
- **Description**: Gets or sets the color that is multiplied with the billboard's texture. This has two common use cases. First, the same white texture may be used by many different billboards, each with a different color, to create colored billboards. Second, the color's alpha component can be used to make the billboard translucent.
- **Default**: `Color.WHITE`
- **Examples**:
```javascript
// Example 1. Assign yellow.
b.color = Cesium.Color.YELLOW;
```
```javascript
// Example 2. Make a billboard 50% translucent.
b.color = new Cesium.Color(1.0, 1.0, 1.0, 0.5);
```
### `disableDepthTestDistance`
- **Type**: `number`
- **Description**: Gets or sets the distance from the camera at which to disable the depth test to, for example, prevent clipping against terrain. When set to zero, the depth test is always applied. When set to Number.POSITIVE_INFINITY, the depth test is never applied.
### `distanceDisplayCondition`
- **Type**: `DistanceDisplayCondition`
- **Description**: Gets or sets the condition specifying at what distance from the camera that this billboard will be displayed. Default Value: `undefined`
### `eyeOffset`
- **Type**: `Cartesian3`
- **Description**: Gets or sets the 3D Cartesian offset applied to this billboard in eye coordinates. Eye coordinates is a left-handed coordinate system, where `x` points towards the viewer's right, `y` points up, and `z` points into the screen. Eye coordinates use the same scale as world and model coordinates, which is typically meters.
- **Examples**:
```javascript
// Below, the billboard is positioned at the center of the Earth but an eye offset makes it always appear on top of the Earth regardless of the viewer's or Earth's orientation.
b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);
```
### `height`
- **Type**: `number | undefined`
- **Description**: Gets or sets a height for the billboard. If undefined, the image height will be used.
### `heightReference`
- **Type**: `HeightReference`
- **Description**: Gets or sets the height reference of this billboard. Default Value: `HeightReference.NONE`
```
--------------------------------
### Create and Configure Cesium Clock
Source: https://cesium.com/learn/cesiumjs/ref-doc/Clock
Demonstrates how to instantiate a Cesium.Clock object with specific start, current, and stop times, along with clock range and step configurations. This example shows a clock that loops on a specific date and runs in real-time.
```javascript
const clock = new Cesium.Clock({
startTime : Cesium.JulianDate.fromIso8601("2013-12-25"),
currentTime : Cesium.JulianDate.fromIso8601("2013-12-25"),
stopTime : Cesium.JulianDate.fromIso8601("2013-12-26"),
clockRange : Cesium.ClockRange.LOOP_STOP,
clockStep : Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER
});
```
--------------------------------
### Initialize App with npm
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Initializes a new Node.js project and creates a package.json file. This is the first step in setting up a new web application using npm.
```bash
npm init
```
--------------------------------
### FrameRateMonitor.fromScene
Source: https://cesium.com/learn/cesiumjs/ref-doc/FrameRateMonitor
Gets or creates a FrameRateMonitor for a given scene. If one doesn't exist, it's created with default settings.
```APIDOC
## static Cesium.FrameRateMonitor.fromScene(scene)
### Description
Gets the `FrameRateMonitor` for a given scene. If the scene does not yet have a `FrameRateMonitor`, one is created with the `FrameRateMonitor.defaultSettings`.
### Method
`static`
### Endpoint
N/A (Static method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
const scene = new Cesium.Scene(viewer.scene);
const monitor = Cesium.FrameRateMonitor.fromScene(scene);
```
### Response
#### Success Response (200)
- **monitor** (FrameRateMonitor) - The scene's `FrameRateMonitor`.
#### Response Example
```json
{
"monitor": "[Instance of FrameRateMonitor]"
}
```
```
--------------------------------
### Initialize ImageBasedLighting with Options
Source: https://cesium.com/learn/cesiumjs/ref-doc/ImageBasedLighting
Demonstrates how to create a new instance of Cesium.ImageBasedLighting, optionally providing configuration options such as scaling factors for diffuse and specular lighting, spherical harmonic coefficients for diffuse color, and a URL to specular environment maps.
```javascript
const imageBasedLighting = new Cesium.ImageBasedLighting({
imageBasedLightingFactor: new Cesium.Cartesian2(0.8, 0.5),
sphericalHarmonicCoefficients: [
new Cesium.Cartesian3(0.1, 0.2, 0.3),
// ... other 8 coefficients
],
specularEnvironmentMaps: 'path/to/your/specular_env.ktx2'
});
```
--------------------------------
### Add Animation to Collection - JavaScript
Source: https://cesium.com/learn/cesiumjs/ref-doc/ModelAnimationCollection
This example demonstrates adding a new animation to a ModelAnimationCollection using the 'add' method. It shows how to specify animation properties like name, start time, and loop behavior. The method returns the newly created ModelAnimation object.
```javascript
const animation = model.activeAnimations.add({
name: 'animationName',
startTime: JulianDate.now(),
loop: ModelAnimationLoop.REPEAT
});
```
--------------------------------
### Setup for Picking in CesiumJS
Source: https://cesium.com/learn/cesiumjs/ref-doc/global
Prepares the CesiumJS scene for picking operations. This function takes the scene, window coordinates, and drawing buffer information as input to configure the picking process.
```javascript
function pickBegin(scene, windowPosition, drawingBufferRectangle, width, height) {
// ... setup logic ...
}
```
--------------------------------
### KmlTourFlyTo Methods
Source: https://cesium.com/learn/cesiumjs/ref-doc/KmlTourFlyTo
Provides methods for interacting with the KmlTourFlyTo object, including getting camera options, playing the transition, and stopping it.
```APIDOC
## KmlTourFlyTo Methods
### getCameraOptions(cameraOptions)
#### Description
Returns options for `Camera#flyTo` or `Camera#flyToBoundingSphere` depending on the `view` type.
#### Parameters
* `cameraOptions` (object) - Optional - Options to merge with the generated options. See `Camera#flyTo` for details.
#### Returns
`object` - `Camera#flyTo` or `Camera#flyToBoundingSphere` options.
### play(done, camera, cameraOptions)
#### Description
Plays this playlist entry, initiating the camera transition.
#### Parameters
* `done` (KmlTourFlyTo.DoneCallback) - Required - A function to be called when playback ends.
* `camera` (Camera) - Required - The Cesium camera instance.
* `cameraOptions` (object) - Optional - Additional options to be merged with camera flyTo options. See `Camera#flyTo`.
### stop()
#### Description
Stops the execution of the current entry, canceling any ongoing camera flyTo operations.
```
--------------------------------
### Create Google Photorealistic 3D Tileset
Source: https://cesium.com/learn/cesiumjs/ref-doc/global
This example shows how to create and add a Google Photorealistic 3D Tileset to a CesiumJS viewer. It requires the `onlyUsingWithGoogleGeocoder` option to be true and optionally accepts a Google Maps API key. Ensure you have the necessary API key and geocoder setup.
```javascript
const viewer = new Cesium.Viewer("cesiumContainer", {
geocoder: Cesium.IonGeocodeProviderType.GOOGLE
});
try {
const tileset = await Cesium.createGooglePhotorealistic3DTileset({
onlyUsingWithGoogleGeocoder: true,
});
viewer.scene.primitives.add(tileset));
} catch (error) {
console.log(`Error creating tileset: ${error}`);
}
```
```javascript
// Use your own Google Maps API key
Cesium.GoogleMaps.defaultApiKey = "your-api-key";
const viewer = new Cesium.Viewer("cesiumContainer". {
geocoder: Cesium.IonGeocodeProviderType.GOOGLE
});
try {
const tileset = await Cesium.createGooglePhotorealistic3DTileset({
onlyUsingWithGoogleGeocoder: true,
});
viewer.scene.primitives.add(tileset));
} catch (error) {
console.log(`Error creating tileset: ${error}`);
}
```
--------------------------------
### Listen for Initial Tiles Loaded Event in VoxelPrimitive
Source: https://cesium.com/learn/cesiumjs/ref-doc/VoxelPrimitive
This example shows how to attach a listener to the `initialTilesLoaded` event for a VoxelPrimitive. This event is triggered once, after all tiles in the initial view are loaded and rendered. It's helpful for performing setup tasks or initializations that depend on the first set of voxel data being available.
```javascript
voxelPrimitive.initialTilesLoaded.addEventListener(function() {
console.log('Initial tiles are loaded');
});
```
--------------------------------
### Set Cesium3DTileStyle pointSize with a conditional expression
Source: https://cesium.com/learn/cesiumjs/ref-doc/Cesium3DTileStyle
This example shows how to set the pointSize property of a Cesium3DTileStyle using a conditional expression. The expression evaluates the 'Temperature' property of a feature and sets the point size to 2.0 if the temperature is above 90, otherwise it sets it to 1.0. The 'evaluate' method can be used to get the resulting number.
```javascript
const style = new Cesium3DTileStyle({
pointSize : '(${Temperature} > 90) ? 2.0 : 1.0'
});
style.pointSize.evaluate(feature); // returns a Number
```
--------------------------------
### JavaScript Entry Point
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Defines the entry point for the webpack build process. This JavaScript file is where webpack starts bundling the application's code.
```javascript
console.log('Hello World!');
```
--------------------------------
### Configure Cesium Base URL
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-quickstart
This JavaScript snippet demonstrates how to configure the `CESIUM_BASE_URL` global variable, which is required when using CesiumJS with a module bundler. This variable must point to the URL where CesiumJS's static files (like workers and SVG icons) are served. This configuration needs to happen before CesiumJS is imported.
```javascript
window.CESIUM_BASE_URL = '/static/Cesium/';
```
--------------------------------
### Initialize CustomHeightmapTerrainProvider with CesiumJS Viewer
Source: https://cesium.com/learn/cesiumjs/ref-doc/CustomHeightmapTerrainProvider
Demonstrates how to initialize a CesiumJS Viewer with a CustomHeightmapTerrainProvider. This example sets up a 32x32 heightmap tile with all zero heights, effectively creating a flat terrain.
```javascript
const viewer = new Cesium.Viewer("cesiumContainer", {
terrainProvider: new Cesium.CustomHeightmapTerrainProvider({
width: 32,
height: 32,
callback: function (x, y, level) {
return new Float32Array(32 * 32); // all zeros
},
}),
});
```
--------------------------------
### I3sBslExplorerViewModel Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/I3sBslExplorerViewModel
Initializes a new instance of the I3sBslExplorerViewModel class.
```APIDOC
## new Cesium.I3sBslExplorerViewModel(i3sProvider)
### Description
Initializes a new instance of the I3sBslExplorerViewModel class. This view model is used by the `I3SBuildingSceneLayerExplorer` widget.
### Method
Constructor
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// Assuming i3sProvider is an instance of I3SDataProvider
const viewModel = new Cesium.I3sBslExplorerViewModel(i3sProvider);
```
### Response
#### Success Response (200)
N/A (Constructor)
#### Response Example
N/A
```
--------------------------------
### NavigationHelpButtonViewModel Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/NavigationHelpButtonViewModel
Initializes a new instance of the NavigationHelpButtonViewModel class.
```APIDOC
## new Cesium.NavigationHelpButtonViewModel()
### Description
Creates a view model for the `NavigationHelpButton` widget.
### Method
`new` (Constructor)
### Endpoint
N/A (Client-side JavaScript class)
### Parameters
None
### Request Example
```javascript
const navigationHelpButtonViewModel = new Cesium.NavigationHelpButtonViewModel();
```
### Response
#### Success Response (Instance)
- **NavigationHelpButtonViewModel** - An instance of the NavigationHelpButtonViewModel.
#### Response Example
```javascript
// An instance of NavigationHelpButtonViewModel is created and available for use.
```
```
--------------------------------
### Initialize Cesium.Resource with Options
Source: https://cesium.com/learn/cesiumjs/ref-doc/Resource
Demonstrates how to create a new Cesium.Resource instance with various configuration options. This includes setting the URL, proxy, headers, query parameters, and defining a custom retry callback function for failed requests. The retry callback can be used to handle specific error codes, like 403 for token expiration, and attempt to regenerate credentials.
```javascript
function refreshTokenRetryCallback(resource, error) {
if (error.statusCode === 403) {
// 403 status code means a new token should be generated
return getNewAccessToken()
.then(function(token) {
resource.queryParameters.access_token = token;
return true;
})
.catch(function() {
return false;
});
}
return false;
}
const resource = new Resource({
url: 'http://server.com/path/to/resource.json',
proxy: new DefaultProxy('/proxy/'),
headers: {
'X-My-Header': 'valueOfHeader'
},
queryParameters: {
'access_token': '123-435-456-000'
},
retryCallback: refreshTokenRetryCallback,
retryAttempts: 1
});
```
--------------------------------
### DataSourceClock Constructor and Properties
Source: https://cesium.com/learn/cesiumjs/ref-doc/DataSourceClock
Details on how to create a DataSourceClock instance and its configurable properties.
```APIDOC
## DataSourceClock
### Description
Represents desired clock settings for a particular `DataSource`. These settings may be applied to the `Clock` when the DataSource is loaded.
### Constructor
`new Cesium.DataSourceClock()`
### Properties
#### `clockRange` : ClockRange
Gets or sets the desired clock range setting. See `Clock#clockRange`.
#### `clockStep` : ClockStep
Gets or sets the desired clock step setting. See `Clock#clockStep`.
#### `currentTime` : JulianDate
Gets or sets the desired current time when this data source is loaded. See `Clock#currentTime`.
#### `definitionChanged` : Event (readonly)
Gets the event that is raised whenever a new property is assigned.
#### `multiplier` : number
Gets or sets the desired clock multiplier. See `Clock#multiplier`.
#### `startTime` : JulianDate
Gets or sets the desired start time of the clock. See `Clock#startTime`.
#### `stopTime` : JulianDate
Gets or sets the desired stop time of the clock. See `Clock#stopTime`.
```
--------------------------------
### ColorMaterialProperty Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/ColorMaterialProperty
Initializes a new instance of ColorMaterialProperty.
```APIDOC
## new Cesium.ColorMaterialProperty(color)
### Description
A `MaterialProperty` that maps to solid color `Material` uniforms.
### Method
Constructor
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Table
| Name | Type | Default | Description |
|---|---|---|---|
| `color` | Property | `Color.WHITE` | optional The `Color` Property to be used. |
### Request Example
```json
{
"example": "new Cesium.ColorMaterialProperty(new Cesium.Color(1.0, 0.0, 0.0, 1.0))"
}
```
### Response
#### Success Response (200)
None (Constructor)
#### Response Example
None
```
--------------------------------
### Initialize GltfGpmLocal with Direct Storage
Source: https://cesium.com/learn/cesiumjs/ref-doc/GltfGpmLocal
Example of initializing GltfGpmLocal with direct storage. This requires providing anchor points and covariance data specific to direct storage.
```javascript
const gltfGpmLocal = new Cesium.GltfGpmLocal({
storageType: "Direct",
anchorPointsDirect: [
// ... array of AnchorPointDirect objects
],
covarianceDirect: Cesium.Matrix3.fromScale(new Cesium.Cartesian3(1.0, 1.0, 1.0))
});
```
--------------------------------
### WebMercatorTilingScheme Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/WebMercatorTilingScheme
Initializes a new instance of WebMercatorTilingScheme. This tiling scheme is used by Google Maps, Microsoft Bing Maps, and most of ESRI ArcGIS Online.
```APIDOC
## new Cesium.WebMercatorTilingScheme(options)
### Description
A tiling scheme for geometry referenced to a `WebMercatorProjection`, EPSG:3857. This is the tiling scheme used by Google Maps, Microsoft Bing Maps, and most of ESRI ArcGIS Online.
### Method
CONSTRUCTOR
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (object) - Optional. Object with the following properties:
- **ellipsoid** (Ellipsoid) - Optional. The ellipsoid whose surface is being tiled. Defaults to the default ellipsoid.
- **numberOfLevelZeroTilesX** (number) - Optional. The number of tiles in the X direction at level zero of the tile tree. Defaults to `1`.
- **numberOfLevelZeroTilesY** (number) - Optional. The number of tiles in the Y direction at level zero of the tile tree. Defaults to `1`.
- **rectangleSouthwestInMeters** (Cartesian2) - Optional. The southwest corner of the rectangle covered by the tiling scheme, in meters. If this parameter or `rectangleNortheastInMeters` is not specified, the entire globe is covered in the longitude direction and an equal distance is covered in the latitude direction, resulting in a square projection.
- **rectangleNortheastInMeters** (Cartesian2) - Optional. The northeast corner of the rectangle covered by the tiling scheme, in meters. If this parameter or `rectangleSouthwestInMeters` is not specified, the entire globe is covered in the longitude direction and an equal distance is covered in the latitude direction, resulting in a square projection.
### Request Example
```json
{
"ellipsoid": "WGS84",
"numberOfLevelZeroTilesX": 2,
"numberOfLevelZeroTilesY": 2,
"rectangleSouthwestInMeters": {
"x": -20000000,
"y": -20000000
},
"rectangleNortheastInMeters": {
"x": 20000000,
"y": 20000000
}
}
```
### Response
#### Success Response (200)
This is a constructor, so it returns an instance of `WebMercatorTilingScheme`.
#### Response Example
(Instance of WebMercatorTilingScheme)
```
--------------------------------
### Cesium.Interval Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/Interval
Creates and returns a new Interval object. An interval is defined by a start and stop value, representing a closed interval [start, stop].
```APIDOC
## new Cesium.Interval(start, stop)
### Description
Represents the closed interval [start, stop].
### Method
Constructor
### Endpoint
N/A (Class Constructor)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **start** (number) - Optional - The beginning of the interval. Defaults to `0.0`.
- **stop** (number) - Optional - The end of the interval. Defaults to `0.0`.
### Request Example
```javascript
const interval1 = new Cesium.Interval(); // Defaults to [0.0, 0.0]
const interval2 = new Cesium.Interval(10.0, 20.0); // Represents [10.0, 20.0]
```
### Response
#### Success Response (200)
N/A (Constructor returns an object)
#### Response Example
```json
{
"start": 10.0,
"stop": 20.0
}
```
### Members
#### start : number
### Description
The beginning of the interval.
### Default Value
`0.0`
#### stop : number
### Description
The end of the interval.
### Default Value
`0.0`
```
--------------------------------
### BingMapsGeocoderService Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/BingMapsGeocoderService
Initializes a new instance of the BingMapsGeocoderService with optional configuration.
```APIDOC
## new Cesium.BingMapsGeocoderService(options)
### Description
Provides geocoding through Bing Maps.
### Method
CONSTRUCTOR
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **options** (object) - Required - Object with the following properties:
* **key** (string) - Required - A key to use with the Bing Maps geocoding service
* **culture** (string) - Optional - A Bing Maps Culture Code to return results in a specific culture and language.
### Request Example
```json
{
"options": {
"key": "YOUR_BING_MAPS_API_KEY",
"culture": "en-US"
}
}
```
### Response
#### Success Response (200)
This is a constructor, it does not return a response in the traditional sense.
#### Response Example
N/A
### See:
* Microsoft Bing Maps Platform APIs Terms Of Use
```
--------------------------------
### Model Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/Model
Provides information about the Model constructor and its usage. It is recommended to use `Model.fromGltfAsync` instead of calling the constructor directly.
```APIDOC
## Model Constructor
### Description
Constructs a Model. To construct a Model, call `Model.fromGltfAsync`. Do not call the constructor directly. A 3D model based on glTF, the runtime asset format for WebGL, OpenGL ES, and OpenGL.
### Method
`new Cesium.Model()`
### Endpoint
N/A (Constructor)
### Parameters
None (Use `Model.fromGltfAsync`)
### Request Example
N/A
### Response
#### Success Response (N/A)
N/A
#### Response Example
N/A
### Supported glTF Extensions
* AGI_articulations
* CESIUM_primitive_outline
* CESIUM_RTC
* EXT_instance_features
* EXT_mesh_features
* EXT_mesh_gpu_instancing
* EXT_mesh_primitive_restart
* EXT_meshopt_compression
* EXT_structural_metadata
* EXT_texture_webp
* KHR_draco_mesh_compression
* KHR_techniques_webgl
* KHR_materials_common
* KHR_materials_pbrSpecularGlossiness
* KHR_materials_unlit
* KHR_mesh_quantization
* KHR_texture_basisu
* KHR_texture_transform
* WEB3D_quantized_attributes
* NGA_gpm_local (experimental)
### Notes
For models with compressed textures using the KHR_texture_basisu extension, power of 2 textures are recommended for maximum compatibility.
```
--------------------------------
### InfoBox Constructor
Source: https://cesium.com/learn/cesiumjs/ref-doc/InfoBox
Initializes a new instance of the InfoBox widget. This widget is used for displaying information or a description within a specified container.
```APIDOC
## new Cesium.InfoBox(container)
### Description
Initializes a new instance of the InfoBox widget. This widget is used for displaying information or a description within a specified container.
### Method
Constructor
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* **container** (Element | string) - Required - The DOM element or ID that will contain the widget.
### Throws
* DeveloperError - Element with id "container" does not exist in the document.
### Request Example
```javascript
const infoBox = new Cesium.InfoBox('#myInfoBoxContainer');
```
### Response
#### Success Response (200)
N/A (Constructor)
#### Response Example
N/A (Constructor)
```
--------------------------------
### Listen for Model Animation Start Event
Source: https://cesium.com/learn/cesiumjs/ref-doc/ModelAnimation
This JavaScript code demonstrates how to attach an event listener to the 'start' event of a Cesium ModelAnimation. The listener logs the animation's name to the console when the animation begins. This is useful for triggering other actions, like sound effects or particle systems, upon animation start.
```javascript
animation.start.addEventListener(function(model, animation) {
console.log(`Animation started: ${animation.name}`);
});
```
--------------------------------
### Basic Webpack Configuration
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Configures webpack to bundle the application. It specifies the context, entry point, and output file name and path.
```javascript
const path = require('path');
const webpack = require('webpack');
module.exports = {
context: __dirname,
entry: {
app: './src/index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
}
};
```
--------------------------------
### Define npm build script
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Adds a 'build' script to package.json that executes the webpack build process using the local webpack installation and the specified configuration file.
```json
"scripts": {
"build": "node_modules/.bin/webpack --config webpack.config.js"
}
```
--------------------------------
### Run npm build command
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Executes the build script defined in package.json, initiating the webpack bundling process. This command generates the application's assets, including 'app.js' and 'index.html', into the 'dist' folder.
```bash
npm run build
```
--------------------------------
### Installing and Configuring strip-pragma-loader
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-webpack
Details the installation and configuration of `strip-pragma-loader` to remove developer-specific pragmas from CesiumJS source files during the build process. This is done by setting `debug: false` in the loader options.
```javascript
npm install strip-pragma-loader --save-dev
```
```javascript
rules: [{
// Strip cesium pragmas
test: /\.js$/,
enforce: 'pre',
include: path.resolve(__dirname, cesiumSource),
use: [{
loader: 'strip-pragma-loader',
options: {
pragmas: {
debug: false
}
}
}]
}]
```
--------------------------------
### Get VelocityOrientationProperty Value (JavaScript)
Source: https://cesium.com/learn/cesiumjs/ref-doc/VelocityOrientationProperty
Illustrates how to retrieve the Quaternion value of a VelocityOrientationProperty at a specific time. This method allows you to get the calculated orientation for a given JulianDate, optionally storing it in a provided result object.
```javascript
const quaternion = velocityOrientationProperty.getValue(time, result);
```
--------------------------------
### Set Specular Environment Maps
Source: https://cesium.com/learn/cesiumjs/ref-doc/ImageBasedLighting
Illustrates how to assign a URL to a KTX2 file containing a cube map for specular lighting and its convoluted mipmaps to the `specularEnvironmentMaps` property of an ImageBasedLighting instance.
```javascript
const imageBasedLighting = new Cesium.ImageBasedLighting();
imageBasedLighting.specularEnvironmentMaps = 'path/to/your/specular_env.ktx2';
```
--------------------------------
### Style Particle Start and End Colors
Source: https://cesium.com/learn/cesiumjs/-learn/cesiumjs-particle-systems
Defines the starting and ending colors for particles in a CesiumJS system, allowing for color transitions over their lifetime. This can create fading or color-changing effects. Alpha values control transparency.
```javascript
startColor: Cesium.Color.LIGHTSEAGREEN.withAlpha(0.7),
endColor: Cesium.Color.WHITE.withAlpha(0.0),
```
--------------------------------
### Create GoogleEarthEnterpriseTerrainProvider from Metadata (JavaScript)
Source: https://cesium.com/learn/cesiumjs/ref-doc/GoogleEarthEnterpriseTerrainProvider
Demonstrates how to create a GoogleEarthEnterpriseTerrainProvider instance by first fetching metadata from a URL and then passing that metadata to the `fromMetadata` static method. This is the recommended way to instantiate the provider, as the constructor should not be called directly.
```javascript
const geeMetadata = await GoogleEarthEnterpriseMetadata.fromUrl("http://www.example.com");
const gee = Cesium.GoogleEarthEnterpriseTerrainProvider.fromMetadata(geeMetadata);
```
--------------------------------
### Create Globally Unique Identifier (GUID)
Source: https://cesium.com/learn/cesiumjs/ref-doc/global
This function generates a universally unique identifier (UUID) string. GUIDs are 128-bit long and are guaranteed to be unique across space and time. This is useful for creating unique keys or identifiers within an application.
```javascript
this.guid = Cesium.createGuid();
```
--------------------------------
### HomeButton.container Member
Source: https://cesium.com/learn/cesiumjs/ref-doc/HomeButton
This member gets the parent container of the HomeButton widget.
```APIDOC
## HomeButton.container
### Description
Gets the parent container.
### Method
Getter
### Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **container** (Element) - The parent container element.
#### Response Example
```json
{
"container": ""
}
```
```