Angular9でOpenLayersを使う


Angular9 + OpenLayersで地図を表示させる

AngularとOpenLayersを使ってWebアプリケーションを作る機会がありましたので、クイックスタートガイドとして使えるようにまとめてみました。今回はAngularにOpenLayersを導入して地図を表示するところまで紹介します。本記事ではオンラインIDEを使用するため、npm等を使用したパッケージインストールに関しては記述しません。

使用ライブラリ等

Angularとは

Googleと個人や企業のコミュニティによって開発されているTypeScriptベースのオープンソースのフロントエンドWebアプリケーションフレームワークである(https://ja.wikipedia.org/wiki/Angular)

OpenLayersとは

ブラウザで地図データを表示する、JavaScriptで組まれたオープンソースライブラリである(https://ja.wikipedia.org/wiki/OpenLayers)

プロジェクトを作成する

  1. CodeSandboxでAngularプロジェクトの作成を選択する。
  2. 画面左下のadd dependencyをクリックするとポップアップウインドウが表示されるので、検索のテキストボックスにolと入力し、検索結果からOpenLayersをインストールする。

これでライブラリのインストールは完了です。
ディレクトリ構成(使う部分のみ)は以下のようになっています。
src
├ app
  ├ app.component.ts
  ├ app.component.css
  ├ app.component.html
  └ (app.module.ts)

OpenLayersを使って地図を表示する

OpenLayersの公式サイトのチュートリアルのコードに手を加えて使いました。
https://openlayers.org/en/latest/doc/quickstart.html
Angularではクロスサイトスクリプティング対策として、htmlファイル内でscriptタグの使用をデフォルトで禁止しています。そのため上記のチュートリアルのコードをhtmlファイルに直接コピーペーストして使うことができません。その代わりにタイプスクリプトファイル内で実装して呼び出せるようにしてあげましょう。

パッケージのインポート

//app.component.ts
import { Component, OnInit } from "@angular/core";
import "ol/ol.css"; //地図のスタイル用css
import { Map, View } from "ol";  
import { OSM } from "ol/source"; //Layer source for the OpenStreetMap tile server.
import { fromLonLat } from "ol/proj";  //Transforms a coordinate from longitude/latitude to a different projection.
import { Tile } from "ol/layer";

OnInitに関して詳しいことはAngularのライフサイクルについて参照してください。コンポーネントの初期化時に一度のみ呼び出されるメソッドです。

ngOnInitの実装

//app.component.ts

export class AppComponent implements OnInit {
  title = "OpenLayers";
  //東京スカイツリーの経度緯度
  skytree = [139.81083333, 35.71000138];

  map:Map;

  ngOnInit() {
    this.map = new Map({
      target: "map", //id="map"を含むhtmlタグをターゲットに指定
      layers: [
        new Tile({
          source: new OSM()
        })
      ],
      view: new View({
        center: fromLonLat(this.skytree),
        zoom: 15
      })
    });
  }
}

htmlファイル

<!--app.component.html-->

<div class="navigation">
  <h1>
    {{ title }}
  </h1>
</div>

<!--マップの埋め込み-->
<div id="map" class="map"></div> 

cssファイル

.navigation {
  color: white;
  text-align: center;
  line-height: 50px;
  height: 7vh;
  background-color: black;
}

.map {
  width: 100%;
  height: 93vh;
}

地図の高さはウインドウの大きさの93%に設定しています。app.component.ts内でol.cssも追加しています。

地図の表示

CodeSandboxでは右半分のウインドウに自動で実行結果を表示してくれます。下の写真のようになっていれば正常に動作しています。

続きのコンテンツ

地図上でのマーカー表示の仕方: 「Angular9でOpenLayersを使う(2)