在Angular9中使用OpenLayers

使用Angular9 + OpenLayers来显示地图

我有机会使用Angular和OpenLayers来开发Web应用程序,所以我整理了一个可以作为快速入门指南的内容。本文将介绍如何在Angular中引入OpenLayers并展示地图。由于本文使用在线IDE,因此不会涉及使用npm等进行软件包安装的描述。

使用库等

    • Angular9: https://angular.io/

OpenLayers v6.3.1: https://openlayers.org/

CodeSandbox: Online IDE: https://codesandbox.io/

Angular 是什么?

Angular是一个基于TypeScript的开源前端Web应用程序框架,由个人和企业社区与Google共同开发。(https://ja.wikipedia.org/wiki/Angular)

OpenLayers是什么

使用浏览器来显示地图数据的是一款使用JavaScript编写的开源库(https://ja.wikipedia.org/wiki/OpenLayers)。

创建一个项目

Screen Shot 2020-06-04 at 17.10.14.png

这样库的安装就完成了。
目录结构(仅列出使用部分)如下:
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文件中使用。相反,让我们在TypeScript文件中实现并调用它。

导入包裹

//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";

请参考Angular的生命周期函数了解更多关于OnInit的相关信息。这是一个在组件初始化时仅被调用一次的方法。

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。

显示地图

Screen Shot 2020-06-04 at 18.16.06.png

继续的内容

「Angular9使用OpenLayers的地图标记显示方法:(2)」

广告
将在 10 秒后关闭
bannerAds