要點
- 圖層設置
設置兩個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也可以。