Leaflet 简单测距

发布时间:2023-12-26 16:54:28

要点

  • 图层设置
    设置两个polyline图层,一个用来绘制click生成的线,一个用来绘制最后一个clickmousemove之间的动态线段
  • 事件处理
    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也可以。

文章来源:https://blog.csdn.net/dahongdahong/article/details/106516868
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。