目标:实现如图地图,并封装为组件
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

相关文章: