1、安装
1.通过npm安装
npm i leaflet.pm
2.引入
import 'leaflet.pm';
import 'leaflet.pm/dist/leaflet.pm.css';
参考:leaflet.pm - npm (npmjs.com)
2、部分代码
if (map) {
map.pm.addControls({
position: 'topleft',
drawPolygon: true, // 添加绘制多边形
drawMarker: true, // 添加按钮以绘制标记
drawCircleMarker: false, // 添加按钮以绘制圆形标记
drawPolyline: true, // 添加按钮绘制线条
drawCircle: true, // 添加按钮绘制圆圈
editMode: true, // 添加按钮编辑多边形
dragMode: true, // 添加按钮拖动多边形
cutPolygon: false, // 添加一个按钮以删除图层里面的部分内容
removalMode: true // 清除图层
});
map.on('pm:create', (e) => {
console.log(e)
console.log(e.shape)
// 点:经纬度
if (e.shape === 'Marker') {
const marker = e.layer; // 获得创建的标记
marker.on('click', () => { // 标记的Marker点击后,加上弹窗
const latLng = marker.getLatLng(); // 获取marker的经纬度
L.popup()
.setLatLng(marker.getLatLng())
.setContent(`<p>Lat: ${latLng.lat}</p> <p>Lng: ${latLng.lng}</p>`) // 显示经纬度
.openOn(map);
});
}
// 线:距离
if (e.shape === 'Line') {
const line = e.layer;
line.on('click', () => {
const latlngs = line.getLatLngs();
let totalDistance = 0;
for (let i = 0; i < latlngs.length - 1; i++) {
totalDistance += latlngs[i].distanceTo(latlngs[i + 1]);
}
L.popup()
.setLatLng(line.getLatLngs()[0]) // 设置在线的第一个点位置显示弹窗
.setContent(`<p>Total distance: ${totalDistance} meters</p>`) // 显示总距离
.openOn(map);
});
}
// 圆:面积
if (e.shape === 'Circle') {
const circle = e.layer;
circle.on('click', () => {
const radius = circle.getRadius(); // 获取半径
const area = Math.PI * Math.pow(radius, 2); // 计算面积
L.popup()
.setLatLng(circle.getLatLng())
.setContent(`<p>Area: ${area} square meters</p>`)
.openOn(map);
});
}
// 多边形:面积
if (e.shape === 'Rectangle' || e.shape === 'Polygon') {
const rectangle = e.layer;
rectangle.on('click', () => {
const latlngs = rectangle.getLatLngs();
let area = 0;
for (let i = 0; i < latlngs[0].length - 1; i++) {
area += latlngs[0][i].distanceTo(latlngs[0][i + 1]) * latlngs[0][i].lng * 2;
}
area = Math.abs(area) / 2;
L.popup()
.setLatLng(rectangle.getBounds().getCenter())
.setContent(`<p>Area: ${area} square meters</p>`)
.openOn(map);
});
}
});
}
3、效果