在做地图应用时,有时需要根据指定的坐标来画一个圆形区域,比如签到打卡类的应用,此时我们可以使用 leaflet.Circle
来在在指定坐标上创建一个圆并添加到的地图上,其中可以通过 radius
属性可以指定区域半径,比如:
const circle = leaflet.circle([lat, lng], {
color: 'red',
fillColor: 'red',
fillOpacity: 0.5,
radius: 100,
}).addTo(this.map);
完整例子如下
import { Component, OnInit, AfterViewInit } from "@angular/core";
import * as leaflet from "leaflet";
@Component({
selector: "app-map-circle",
templateUrl: "./map-circle.component.html",
styleUrls: ["./map-circle.component.css"],
})
export class MapCircleComponent 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], 16);
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);
let marker: leaflet.Marker | null = null;
let circle: leaflet.Circle | null = null;
this.map.on("click", (e) => {
console.log(e.latlng);
if (marker) {
this.map.removeLayer(marker);
}
const icon = leaflet.icon({
iconUrl: "media/marker-icon.png",
iconSize: [25, 41],
iconAnchor: [12, 41]});
marker = leaflet.marker([e.latlng.lat, e.latlng.lng], {icon: icon}).addTo(this.map);
if (circle) {
this.map.removeLayer(circle);
}
circle = this.createCircle(e.latlng.lat, e.latlng.lng, "red").addTo(this.map);
});
}
private createCircle(lat: number, lng: number, color: string): leaflet.Circle {
return leaflet.circle([lat, lng], {
color: color,
fillColor: color,
fillOpacity: 0.5,
radius: 100,
});
}
}