Angular+Leaflet 封装map component

本文介绍了如何在Angular应用中封装一个使用Leaflet的地图组件。通过引入leaflet库,创建组件模板并设置地图显示,以及在父组件中使用该组件来展示marker信息。为了确保地图完整加载,还需在index.html中引入相关样式和脚本文件。完整代码可在指定链接获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目标:实现如图地图,并封装为组件
在这里插入图片描述

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/leaflet@1.4.0/dist/leaflet.css" />

<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"></script>

大致的流程就是这样子的,如果想要更完整的代码:
https://download.youkuaiyun.com/download/qq_32490291/11160081

others:
leaflet -npm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值