DEV Community

David Akim
David Akim

Posted on

Using CesiumJS with Angular

In this lesson, we will go through the steps of integrating CesiumJS with Angular. CesiumJS is an open source JavaScript library for creating 3D globes and maps. At the end of the lesson you should be able to do a simple plot with CesiumJS.

Prerequisite

  • Must be familiar with Angular

Create a new angular project called angular-plotly. In the command terminal type the following.

ng new angular-cesium
Enter fullscreen mode Exit fullscreen mode

When prompted “Would you like to add Angular routing? (y/N)”, you can type either y or N and hit Enter on the keyboard. When prompted “Which stylesheet format would you like to use?”, you can select CSS.

Navigate into the angular-cesium directory. In the command terminal type the following.

cd angular-cesium
Enter fullscreen mode Exit fullscreen mode

Create a new component called cesium-component. In the command terminal type the following.

ng generate component cesium-component
Enter fullscreen mode Exit fullscreen mode

Open app.component.html ,delete all the contents and add the following line

<app-cesium-component></app-cesium-component>
Enter fullscreen mode Exit fullscreen mode

Go to CesiumJS. There will be 2 options:

  • Install from NPM
  • Download CesiumJS

For this demonstration, download CesiumJS and unzip the file.

Copy the Cesium folder (from the unzipped folder) in Cesium-1.96/Build to angular-cesium/src/assets (your angular project).

Open the angular.json file and modify the styles and scripts as seen below.

"styles": [
  "src/styles.css",
  "src/assets/Cesium/Widgets/widgets.css"
],
"scripts": [
  "src/assets/Cesium/Cesium.js"
]
Enter fullscreen mode Exit fullscreen mode

If you are having difficulty finding the specific lines to modify, simply search for the keyword scripts. This is the complete code.

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-cesium": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:application": {
          "strict": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/angular-cesium",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "src/assets/Cesium/Widgets/widgets.css"
            ],
            "scripts": [
              "src/assets/Cesium/Cesium.js"
            ]
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "angular-cesium:build:production"
            },
            "development": {
              "browserTarget": "angular-cesium:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular-cesium:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "src/assets/Cesium/Widgets/widgets.css"
            ],
            "scripts": [
              "src/assets/Cesium/Cesium.js"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "angular-cesium"
}
Enter fullscreen mode Exit fullscreen mode

Create a new service called cesium. This service will contain the plot functions. In the command terminal type the following.

ng generate service cesium
Enter fullscreen mode Exit fullscreen mode

You will need to create an account in Cesium here.

Go to Access Tokens and click Create token. Give it a name and click Create. In this demonstration the name is cesiumtest.

Image description

Select the token you just created and copy the the token.

Image description

Open cesium.service.ts and make the following changes as seen below. For Cesium.Ion.defaultAccessToken, paste your token. Here we created a function called plotPoints which takes an argument div. This is the id of the div tag used for displaying the plot. Three points will be plotted at the following coordinates

  • Latitude: 40.03883, Longitude: -75.59777, Color: Red
  • Latitude: 35.14, Longitude: -80.5, Color: Blue
  • Latitude: 25.46, Longitude: -80.12, Color: Yellow

All the points have a pixel size of 16. For more information the Cesium.Cartesian3.fromDegrees method on visit this link.

import { Injectable } from '@angular/core';
declare let Cesium: any;
// import * as Cesium from '../assets/js/Cesium.js';
Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2MWZlOTZjMy1iYjhiLTRkYjktOWEyYS0xYjllYWM4NmQ3YjYiLCJpZCI6ODM1MzksImlhdCI6MTY2MTU0NTg0MX0.PBHIiiQPO0_kfthCfRxp4VVGlhFZp4BMKIeILBwYuqk";@Injectable({
  providedIn: 'root'
})
export class CesiumService {constructor() { }
  private viewer: any;plotPoints(div:string){
    this.viewer = new Cesium.Viewer(div);
    this.viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
      point: {
        color: Cesium.Color.RED,
        pixelSize: 16,
      },
    });
    this.viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(-80.5, 35.14),
      point: {
        color: Cesium.Color.BLUE,
        pixelSize: 16,
      },
    });
    this.viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(-80.12, 25.46),
      point: {
        color: Cesium.Color.YELLOW,
        pixelSize: 16,
      },
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Open cesium-component.component.ts and make the following changes as seen below. When the page loads, 3 points will be plotted on a 3D globe. The id of the div displaying the plot is “cesium”.

import { Component, OnInit } from '@angular/core';
import { CesiumService } from '../cesium.service';@Component({
  selector: 'app-cesium-component',
  templateUrl: './cesium-component.component.html',
  styleUrls: ['./cesium-component.component.css']
})
export class CesiumComponentComponent implements OnInit {constructor(private cesium: CesiumService) { }ngOnInit(): void {
    this.cesium.plotPoints("cesium");
  }}
Enter fullscreen mode Exit fullscreen mode

Open cesium-component.component.html and make the following changes. Here the div with the id cesium is created.

<div id="cesium"></div>
Enter fullscreen mode Exit fullscreen mode

Open index.html from angular-cesium/src and make the following changes as seen below.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularCesium</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script>
    window.CESIUM_BASE_URL = 'http://localhost:4200/assets/Cesium/';
  </script>
</head>
<body>
  <app-root></app-root>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the command terminal type the following.

ng serve
Enter fullscreen mode Exit fullscreen mode

On your browser go to http://localhost:4200/. You should see the plot.

Image description

This is the end of the lesson. For more examples on CesiumJS, check the documentation here.

Top comments (0)