以下是一个在Angular和Leaflet中点击地图添加标记并获取坐标的解决方法的代码示例:
首先,在你的Angular项目中安装Leaflet和@types/leaflet库:
npm install leaflet @types/leaflet
接下来,在你的组件中引入Leaflet库:
import { Component, OnInit } from '@angular/core';
import * as L from 'leaflet';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
map: L.Map;
ngOnInit() {
this.initializeMap();
}
initializeMap() {
this.map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: 'Map data © OpenStreetMap contributors'
}).addTo(this.map);
this.map.on('click', (e) => {
this.addMarker(e.latlng);
});
}
addMarker(latlng: L.LatLng) {
L.marker(latlng).addTo(this.map);
console.log('Clicked at: ' + latlng);
}
}
然后,在你的HTML模板中添加一个用于显示地图的容器:
最后,在你的CSS文件中设置地图容器的宽度和高度:
#map {
width: 100%;
height: 400px;
}
这样,当你在地图上点击时,会在点击位置添加一个标记,并在控制台上输出点击位置的坐标。