Leaflet使用SVG创建动态文字图标

接前一篇文章,在 Leaflet 中,我们可以使用 L.marker(...).addTo(map)L.circle(...).addTo(map) 在地图上创建一个标记(参考:https://leafletjs.com/examples/quick-start/),比如:

var marker = L.marker([51.5, -0.09]).addTo(map);var circle = L.circle([51.508, -0.11], {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5,
    radius: 500
}).addTo(map);

但是如果我们想在标记上添加文字就没法实现了,比如我们在标记上添加一些统计数字。此时,我们可以通过来插入一个svg图片来实现这个功能。比如:

const circleSVGHtml = `<svg version="1.2" baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" width="250" height="250">
					<circle cx="125" cy="125" r="100" fill="blue"/>
					<text x="50%" y="50%" text-anchor="middle" fill="white" font-size="100px" font-family="Arial" dy=".2em">
					123
					</text>
				</svg>`;
const iconURL = "data:image/svg+xml," + encodeURIComponent(circleSVGHtml);
const circleIcon = leaflet.icon({
  iconUrl: iconURL,
  iconSize: [30, 30],
});
const marker = leaflet
  .marker([51.5, -0.09], { icon: circleIcon })
  .addTo(this.map);

完整的 map.component.ts 文件如下,其它代码参考前一篇文章。

import { Component, OnInit, AfterViewInit } from "@angular/core";
import * as leaflet from "leaflet";

@Component({
  selector: "app-map",
  templateUrl: "./map.component.html",
  styleUrls: ["./map.component.css"],
})
export class MapComponent implements OnInit, AfterViewInit {
  map!: leaflet.Map;
  constructor() {}

  ngOnInit(): void {}

  ngAfterViewInit(): void {
    this.initMap();
  }

  private initMap(): void {
    this.map = leaflet.map("map").setView([51.5, -0.09], 13);

    const tiles = leaflet.tileLayer(
      "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
      {
        maxZoom: 19,
        attribution:
          '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      },
    );
    tiles.addTo(this.map);

    const circleSVGHtml = `<svg version="1.2" baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" width="250" height="250">
					<circle cx="125" cy="125" r="100" fill="blue"/>
					<text x="50%" y="50%" text-anchor="middle" fill="white" font-size="100px" font-family="Arial" dy=".2em">
					123
					</text>
				</svg>`;
    const iconURL = "data:image/svg+xml," + encodeURIComponent(circleSVGHtml);
    const circleIcon = leaflet.icon({
      iconUrl: iconURL,
      iconSize: [30, 30],
    });
    const marker = leaflet
      .marker([51.5, -0.09], { icon: circleIcon })
      .addTo(this.map);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值