接前一篇文章,在 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:
'© <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);
}
}