Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 calledangular-plotly. In the command terminal type the following.

ng new angular-cesium
Enter fullscreen modeExit 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 theangular-cesium directory. In the command terminal type the following.

cd angular-cesium
Enter fullscreen modeExit fullscreen mode

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

ng generate component cesium-component
Enter fullscreen modeExit fullscreen mode

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

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

Go toCesiumJS. There will be 2 options:

  • Install from NPM
  • Download CesiumJS

For this demonstration, download CesiumJS and unzip the file.

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

Open theangular.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 modeExit fullscreen mode

If you are having difficulty finding the specific lines to modify, simply search for the keywordscripts. 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 modeExit fullscreen mode

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

ng generate service cesium
Enter fullscreen modeExit fullscreen mode

You will need to create an account in Cesiumhere.

Go toAccess Tokens and clickCreate token. Give it a name and clickCreate. In this demonstration the name iscesiumtest.

Image description

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

Image description

Opencesium.service.ts and make the following changes as seen below. ForCesium.Ion.defaultAccessToken, paste your token. Here we created a function calledplotPoints which takes an argumentdiv. 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 theCesium.Cartesian3.fromDegrees method on visit thislink.

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 modeExit fullscreen mode

Opencesium-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 modeExit fullscreen mode

Opencesium-component.component.html and make the following changes. Here the div with the idcesium is created.

<div></div>
Enter fullscreen modeExit fullscreen mode

Openindex.html fromangular-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 modeExit fullscreen mode

In the command terminal type the following.

ng serve
Enter fullscreen modeExit fullscreen mode

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

Image description

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a software developer with a background in Electrical and Computer Engineering.
  • Location
    Trinidad and Tobago
  • Joined

More fromDavid Akim

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp