在Angular 9中使用Leaflet js 與 OpenStreetMap地圖

最近剛看保哥的Angular線上課程,剛好六角學院的老師與同學們跟上時事在做口罩地圖,就試著用Angular做作看口罩地圖點此看DEMO展示看GitHub原始碼,本文就簡單講解在Angular上如何使用Leaflet js 與 OpenStreetMap。

因為現在Google Map Api已經開使在收費了,雖然有免費額度,但超過額度就要收費,也不曉得會不會有惡意瀏覽來超過額度這種攻擊荷包的方式,這次便改用Leaflet.js 與OpenStreetMap組合而成的替代方案。

OpenStreetMap是一個非營利基金會營運的開放地圖,提供大眾使用、編輯、共享地圖資訊。OpenStreetMap提供了圖資,而如何使用圖資呢?,例如:以某個中心點為座標顯示地圖、放大縮小地圖、在地圖上標示圖案等等,這些與使用這有關的操作與互動鳩跟Leaflet.js有關了。Leaflet.js是開源的JavaScript地圖函式庫,我們可以將圖資傳給Leaflet.js,藉由操作Leaflet.js來達成剛剛所述的控制地圖、放大、縮小、顯示圖標等操作。

建立專案

首先先新增一個專案

ng new appname --routing --style css

用npm安裝leaflet

npm install leaflet --save

建立元建並命名為map

ng g c map

使用leaflet

在map元件map.component.html中清除<p>map works!</p>並改成 <div id="map"></div>
在map元件map.component.ts中載入leaflet全部組件並命名為L

import * as L from 'leaflet';

constructor()之前加入map成員,並在map元件map.component.ts的初始化方法ngOnInit()中。使用leaflet建立map圖層並載入OpenStreetMap圖資後加進map圖層

export class MapComponent implements OnInit {
  map;

  constructor() { }

  ngOnInit(): void {
    this.map = L.map('map', { center: [25.0249211,121.5075035], zoom: 16 });//指定欲繪製地圖在id為map的元素中,中心座標為[25.0249211,121.5075035],縮放程度為16
    const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    });

    tiles.addTo(this.map);
  }
}

隨後到app.component.html中,清除原先生成內容後,把我們的map元件加入近來

<app-map></app-map>

現在開啟ng serve應該可以看到網頁地圖,但是呈現破碎狀,東缺西缺一塊

因為缺少leaflet的CSS檔
我這邊直接在styles.css檔中把leaflet.css import進來,並直接設定#map、html,body的高度都為100%(不然地圖會顯示不出來)

@import "~leaflet/dist/leaflet.css"
html,body{
  height: 100%;
}
#map {
  height: 100%;
}

設定完CSS後就可以看到地圖了

標上圖標

顯示圖標的方式,可以用變數把圖標儲存起來,來控制圖標開啟或關閉。這段程式碼可以寫在ngOnInit()中的最下方,或者包成一個方法,當有事件時在觸發。

const marker = L
    .marker([25.0249211,121.5075035],{title: '我是座標'})
    .addTo(this.map)
    .bindPopup('<h1>我是彈出視窗</h1>');
marker.openPopup();//開啟彈出視窗

參考資料:
Building Maps in Angular Using Leaflet, Part 1: Generating Maps
Building Maps in Angular using Leaflet, Part 2: The Marker Service
Leaflet + OpenStreetMap 地圖應用開發
示範:使用 Vuejs 結合 Open Street Map 製作口罩地圖

Facebook留言板