polyline
图层,一个用来绘制click
生成的线,一个用来绘制最后一个click
和mousemove
之间的动态线段click
生成点集合,mousemove
生成临时点,dblclick
结束绘制turf.js
计算polyline
距离(也可以使用leaflet自带的distance
方法实现) measure() {
const map = this.$map;
// 避免多次drawing
if (this.drawing) {
return
}
// interactive = false 避免用户双击map无效
const layer = L.polyline([], {
interactive: false
}).addTo(map);
this.layer = layer;
// 绘制mousemove line
const tempLayer = L.polyline([], {
interactive: false
}).addTo(map);
let tempPoints = [];
// 结束绘制
const remove = () => {
layer.remove();
popup.remove();
dblclickHandler();
};
// popup 展示距离
const popup = L.popup({
autoClose: false,
closeButton: false
});
// 自定义 展示框
const setTipText = content => {
const el = document.createElement("div");
el.className = "measure-marker";
const text = document.createElement("span");
text.className = "measure-text";
text.innerHTML = content;
const close = document.createElement("span");
close.className = "measure-close";
close.addEventListener("click", () => {
remove();
});
el.appendChild(text);
el.appendChild(close);
return el;
};
const clickHandler = e => {
layer.addLatLng(e.latlng);
tempPoints[0] = e.latlng;
this.drawing = true
map.doubleClickZoom.disable()
const len = turf.length(layer.toGeoJSON(), { units: "kilometers" });
popup
.setLatLng(e.latlng)
.setContent(setTipText(len.toFixed(2) + " 公里"))
.openOn(map);
};
const mousemoveHandler = e => {
if (tempPoints.length) {
tempPoints[1] = e.latlng;
tempLayer.setLatLngs(tempPoints);
}
};
// 双击结束, 移除事件是良好的编程习惯
const dblclickHandler = e => {
tempPoints = null;
tempLayer.remove();
this.drawing = false
map.doubleClickZoom.enable()
map.off("click", clickHandler);
map.off("mousemove", mousemoveHandler);
map.off("dblclick", dblclickHandler);
};
map.on("click", clickHandler);
map.on("mousemove", mousemoveHandler);
map.on("dblclick", dblclickHandler);
}
??上述代码中的 length
是用来计算距离的,turf.js 中的方法。如果你借助框架(vue、react这类),你可以按需加载:
import length from "@turf/length";
??如果你没借助这类开发框架,你可以直接在html里面引入turf.js,然后将上述代码中的 length
改为 turf.length
<script src='https://unpkg.com/@turf/turf/turf.min.js'></script>
?? Leaflet 提供 distance
方法,用来计算两点间的距离,不采用turf.js也可以。