이전글
2024.01.15 - [GIS] - [3D MAP] 1. 기본 용어 정리
2024.01.16 - [GIS] - [3D MAP] 2. vworld key 발급, Cesium Ion 시작하기
key 도 발급받고 Cesium Ion 에 모델도 올려봤으니 이제 웹에서 호출하여 활용하는 방법만 남았네요!
저는 Angular 프레임 워크와, CesiumJs 를 사용하여 띄워보도록 하겠습니다.
Angular CLI, NPM, Node.js 는 설치 되어 있어야 합니다.
MacOS, VS Code, Angular 17, Node v18.13.0, Cesium 1.113.0
프로젝트 생성
프로젝트를 생성할 경로로 이동하여 다음과 같이 명령어를 입력해 줍니다.
ng n [프로젝트명]
ng n cesium-test
- router 사용
- scss 사용
- ssr 사용 안 함
생성 확인
프로젝트가 잘 생성 됐는지 확인을 해봅시다. VS Code 를 통해 생성한 cesium-test 프로젝트를 열고, 터미널에 명령어를 칩니다.
npm start
localhost:4200 으로 이동하면,
잘 뜨네요 ㅎㅎ
Cesium Install
npm i cesium --force
angular 버전 7이상 부터는 --force / --legacy-peer-deps 둘 중 하나를 선택해서 붙여줘야 합니다.
- --force : 다른 의존 버전들의 추가 설치
- --legacy-peer-deps : 무시하고 설치
개인적으로는 --force 로 사용합니다. 버전도 알아서 맞춰(?) 주니 생각보다 편함..
install 후 package.json 에서 확인 하면 cesium 이 추가된 것을 확인할 수 있습니다.
"dependencies": {
"cesium": "^1.113.0",
}
컴포넌트 생성
src > app 에 cesium 컴포넌트를 생성합니다.
ng g c [컴포넌트명]
ng g c cesium
ng g c [컴포넌트명] --module=app.module
--module=app.module 옵션을 붙이면 app.module 에 자동으로 import 됩니다.
+) Angular 15 버전부터는 독립형 구성요소 선언인 standalone 을 지원합니다. 해당 글에서는 module 파일을 생성하지 않고(모듈에서 구성 요소를 선언할 필요 없이), standalone: true 선언으로 작성하겠습니다.
그럼 cesium 안에 component.html, scss, ts, spec.ts 가 생성된 것을 확인할 수 있습니다. 해당 파일들은 컴포넌트를 생성하면서 만들어진 컴포넌트 구성 요소들 입니다.
- html : cesium.component 표출시 보여지는 HTML 템플릿 파일
- scss : HTML 을 꾸며주는 css
- ts : TypeScript 기반으로 함수를 작성할 수 있는 컴포넌트 파일
- spec.ts : 테스트 파일
컴포넌트 표출하기
앵귤러 프로젝트를 실행하며 보여진 화면은 어디서 작성된 것일까요?
index.html 을 열어보시면 <body> 태그 안에 있는 <app-root> 태그가 보이실겁니다.
<app-root> 는 app.component.html 을 가리키는 HTML 템플릿의 이름. selector 라고 합니다.
app.component.ts 를 보시면 컴포넌트 생성에 필요한 정보를 담고 있는데요.
이때 selector, templateUrl, styleUrls 이 컴포넌트 구성 요소인 html, scss, ts 를 하나로 묶어주는 역할을 합니다.
해당 ts 파일에서 html, scss 를 묶고 다른 템플릿에서 selector 로 import 했을 때 묶여있는 파일의 정보를 같이 읽을 수 있게 말이죠.
index.html 에서 app 컴포넌트의 selector 를 import 했기 때문에, app.component.html 에 작성된 내용이 그대로 표출되는 것입니다.
해당 요소는 컴포넌트를 생성하면 자동으로 입력 됩니다. cesium.component.ts 를 확인해볼까요?
import { Component } from '@angular/core';
@Component({
selector: 'app-cesium', // html 템플릿 이름
standalone: true, // 독립형 컴포넌트 선언
imports: [], // 해당 컴포넌트에서 사용할 모듈
templateUrl: './cesium.component.html', // html 매핑
styleUrl: './cesium.component.scss' // css 매핑
})
export class CesiumComponent {
}
그렇기 때문에, index.html 에서 app.html 을 Import 하여 app.html에 있는 내용이 표출되는 것입니다. 이 과정과 동일하게 위에서 생성한 cesium 컴포넌트를 불러와 표출을 해봅시다.
1) app.component.ts
cesiumcomponent 를 imports 에 추가합니다. app 컴포넌트가 CesiumComponent 구성 요소를 사용한다고 선언하는 과정입니다.
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { CesiumComponent } from './cesium/cesium.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, CesiumComponent], // cesiumcomponent 추가
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
title = 'cesium-test';
}
2) app.component.html
html 내에 있는 모든 태그들을 지우고, 다음과 같이 작성합니다.
<!-- cesium selector import -->
<app-cesium></app-cesium>
저장 후, 화면을 보면 cesium 컴포넌트 html 에 있는 내용이 표출됩니다.
이제 app.component 내에서 cesium 컴포넌트의 영역을 다룰 수 있게 되었습니다.
진짜 Cesium 표출하기 (Cesium 뷰어 로드하기)
이제 cesium 을 띄워보겠습니다.
cesium.component.ts 파일로 이동한 후, implements OnInit 을 추가합니다.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-cesium',
standalone: true,
imports: [],
templateUrl: './cesium.component.html',
styleUrl: './cesium.component.scss'
})
export class CesiumComponent implements OnInit {
}
Angular 생명주기를 이용하기 위해 해당 부분을 추가했습니다. 이 부분은 해당 글에서 다룰 내용은 아니므로 넘어가겠습니다.
그리고 두 개의 코드를 추가합니다.
- constructor () {} : html 태그 속성을 건드리기 위해 필요한 ElementRef 클래스를 의존성 주입하려고 추가
- ngOnInit () {} : OnInit 인터페이스 구현으로 오버라이딩 해야 할 메서드
import { Component, ElementRef, OnInit } from '@angular/core';
@Component({
selector: 'app-cesium',
standalone: true,
imports: [],
templateUrl: './cesium.component.html',
styleUrl: './cesium.component.scss'
})
export class CesiumComponent implements OnInit {
constructor () {} // 추가
ngOnInit() {} // 추가
}
Cesium 을 표출하기 위해 ElementRef 클래스를 주입하고, cesium 라이브러리를 import 합니다.
그리고 ngOnInit() 에 코드 한줄을 추가합니다.
import { Component, ElementRef, OnInit } from '@angular/core';
import * as Cesium from 'cesium'; // cesium 라이브러리 import. 컴포넌트 내에서 Cesium 으로 사용 선언
@Component({
selector: 'app-cesium',
standalone: true,
imports: [],
templateUrl: './cesium.component.html',
styleUrl: './cesium.component.scss'
})
export class CesiumComponent implements OnInit {
constructor (
private el: ElementRef, // 클래스 주입
) {}
ngOnInit() {
const viewer = new Cesium.Viewer(this.el.nativeElement); // cesium 표출
}
}
이제 마지막 작업이 남았습니다.
- cesium 사용을 위한 몇 가지 정적 파일을 서버에서 호스팅 해야 하기 때문에 전역 변수를 통해 BASE_URL 설정
- cesium 의 필수 구성을 Angular 프로젝트에 포함시키는 과정
1) BASE_URL 설정
프로젝트 루트 목록에 있는 main.ts 를 열어줍니다. (맥 기준 vscode 에서 command + p 를 누르면 파일 검색이 가능하니 참고하세요)
다음과 같이 작성합니다.
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
// Cesium base url 추가
(window as any).CESIUM_BASE_URL = '/assets/cesium/';
2) cesium 의 필수 구성 등록
프로젝트 루트 목록에 있는 angular.json 를 열어줍니다.
architect 부분을 보면 assets, styles, scripts 부분이 있습니다.
- assets : cesium 폴더 추가
- styles : cesium css 파일 추가
- scripts : cesiumJs 파일 추가
해당 내용을 추가하는 과정입니다.
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/cesium-test",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets",
// 추가 부분
{
"glob": "**/*",
"input": "node_modules/cesium/Build/Cesium",
"output": "./assets/cesium"
}
// 추가 부분 끝
],
"styles": [
"src/styles.scss",
"node_modules/cesium/Build/Cesium/Widgets/widgets.css" // 추가
],
"scripts": ["node_modules/cesium/Build/Cesium/Cesium.js"] // 추가
},
이제 웹을 열어 확인해봅시다.
성공적으로 띄워졌네요! 생각보다 간단하고 쉽지 않나요?
그렇다면 다음 포스팅에선 Cesium Ion 에 등록했던 모델들을 활용하는 방법에 대해 작성해보겠습니다.
참고
'GIS > Cesium' 카테고리의 다른 글
[3D MAP] 2. vworld key 발급, Cesium Ion 시작하기 (0) | 2024.01.16 |
---|---|
[3D MAP] 1. 기본 용어 정리 (0) | 2024.01.15 |