效果图
鼠标左键按下—>拖动开始绘制区域–>松开绘制完成
(效果跟window桌面拖动出现的框框一样) 😃
直接上代码
//地图初始化
initMap () {
this.map = L.map('chinaMap', {
layers: [
new L.TileLayer("https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}")
],
center: [39.77642556850833, 116.41113281250001],
zoom: 4,
minZoom: 2,
zoomControl: false,
attributionControl: false
});
//绑定鼠标左键按下事件
this.map.on('mousedown',e=>{
if(!event.button){
//禁用地图拖动
this.map.dragging.disable();
//获取起始点
this.juxing.startPoint = e.latlng;
//移动事件
this.map.on('mousemove',m=>{
this.juxing.endPoint = m.latlng;
//判断是否存在矩形对象,保证只留一个
if(this.juxing.object!=null){
//删除临时矩形
this.juxing.object.remove();
}
//创建矩形 添加到地图中[开始坐标,结束坐标]
this.juxing.object = L.rectangle([
this.juxing.startPoint,this.juxing.endPoint
], {color: "#ff7800", weight: 1}).addTo(this.map);
})
}
});
//监听鼠标左键弹起
this.map.on('mouseup',e=>{
if(!event.button){
//开启地图拖拽
this.map.dragging.enable();
//绘制结束后不保留矩形
this.juxing.object.remove();
console.log("开始位置",this.juxing.startPoint,this.juxing.endPoint);
//移除鼠标移动事件
this.map.off('mousemove');
}
})
}