Angular+Leaflet 封裝map component

目標:實現如圖地圖,並封裝爲組件
在這裏插入圖片描述

map.component.ts:

首先,引入leaflet和translate:

import * as L from 'leaflet'; 

import { TranslateService } from '@ngx-translate/core';  //根據語言來加載不同的layer

然後定義下template

@Component({
  selector: 'my-map',
  template: `
    <mat-progress-bar *ngIf="!mapLoad"
      class="example-margin"
      [color]="primary"
      [mode]="determinate"
      [value]="50"
      [bufferValue]="75">
    </mat-progress-bar>
    <div id="box" style="height:100%;display:flex;position:relative;">
      <div id="container" style="position:absolute;top:0;left:0;width:100%;height:100%;display:flex;"></div>
    </div>
  `
})

顯示地圖信息:

  initMap(){
    //leaflet map + google 
    this.LMap = L.map('container').setView([24.4884, 118.12706],this.zoom);
    if (this.translate.currentLang !== 'zh-CN') {
      L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        maxZoom: 20
      }).addTo(this.LMap);
    } else {
      L.tileLayer('http://{s}.google.cn/vt/lyrs=m&x={x}&y={y}&z={z}', {
        maxZoom: 20,
        subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
      }).addTo(this.LMap);
    }
  }
  
  ngOnInit(){
    setTimeout(()=>{    
      this.initMap();
    },100);
  }

引用map component的頁面:app.component.html;

<div class="map-box column">
  <my-map class="column" [markers]="markerList" [zoom]="6" style="flex: 1;width: 100%;max-height: 100%;height:100%;overflow: hidden;"></my-map>
</div>

markers,用來收集存放需要顯示的marker信息;

爲了防止有空白塊或者加載不全的情況,我們要在index.html頁面引入兩個文件:

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />

<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>

大致的流程就是這樣子的,如果想要更完整的代碼:
https://download.csdn.net/download/qq_32490291/11160081

others:
leaflet -npm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章