1.首先,安装leaflet的插件(插件地址:https://leafletjs.com/plugins.html)
npm i leaflet-linear-measurement --save
2.新建一个measurement.js文件
import "leaflet-linear-measurement/src/Leaflet.LinearMeasurement.js";
import "leaflet-linear-measurement/sass/Leaflet.LinearMeasurement.scss";
import L from "leaflet";
var cost_underground = 12.55,
cost_above_ground = 17.89,
html = [
"<table>",
' <tr><td class="cost_label">Cost Above Ground:</td><td class="cost_value">${total_above_ground}</td></tr>',
' <tr><td class="cost_label">Cost Underground:</td><td class="cost_value">${total_underground}</td></tr>',
"</table>",
].join(""),
numberWithCommas = function (x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
var Ruler = L.Control.LinearMeasurement.extend({
layerSelected: function (e) {
/* cost should be in feet */
var distance = e.total.scalar;
if (e.total.unit === "mi") {
distance *= e.sub_unit;
} else if (e.total.unit === "km") {
distance *= 3280.84;
} else if (e.total.unit === "m") {
distance *= 3.28084;
}
var data = {
total_above_ground: numberWithCommas(L.Util.formatNum(cost_above_ground * distance, 2)),
total_underground: numberWithCommas(L.Util.formatNum(cost_underground * distance, 2)),
};
var content = L.Util.template(html, data),
popup = L.popup().setContent(content);
e.total_label.bindPopup(popup, { offset: [45, 0] });
e.total_label.openPopup();
},
});
export default Ruler;
3.在地图的组件中引进:
import Ruler from "@/util/measurement";
4.在需要使用的方法中调用,或者直接在渲染地图初始化中调用
this.map.addControl(
new Ruler({
unitSystem: "metric",
color: "#FF0080",
})
);