Mapbox GL 测距(动态画线 + Tooltip)

话不多说,直接上图和代码!
在这里插入图片描述

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Measure distances</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
  <script src="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js"></script>
  <link href="https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css" rel="stylesheet" />
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
  </style>
</head>

<body>
  <style>
    .distance-container {
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 1;
    }

    .distance-container>* {
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      font-size: 11px;
      line-height: 18px;
      display: block;
      margin: 0;
      padding: 5px 10px;
      border-radius: 3px;
    }

    .mapboxgl-popup-tip {
      border: none;
    }

    .mapboxgl-popup-content {
      padding: 0;
    }

    .tooltip {
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      font-size: 11px;
      line-height: 18px;
      display: block;
      margin: 0;
      padding: 5px 10px;
      border-radius: 3px;
    }

    .result {
      background-color: #ffcc33;
      color: black;
      border: 1px solid white;
    }
  </style>

  <div id="map"></div>
  <div id="distance" class="distance-container"></div>

  <script src="https://npmcdn.com/@turf/turf@5.1.6/turf.min.js"></script>
  <script>
    mapboxgl.accessToken =
      'pk.eyJ1IjoiY2hyaXNtYTI4NTciLCJhIjoiY2s5czhjNGxtMDM4ejNmbGkzNjgzM20wNiJ9.XFgSSvElyw0BY7bvky5NwA';
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [2.3399, 48.8555],
      zoom: 12
    });

    // GeoJSON object to hold our measurement features
    // 存储正在绘制的线要素
    var geojson = {
      'type': 'FeatureCollection',
      'features': []
    };

    // 存储已经绘制完成的线要素
    var oldgeojson = {
      'type': 'FeatureCollection',
      'features': []
    };

    var helpTooltip = new mapboxgl.Popup({
      closeButton: false,
      anchor: 'top-left',
      offset: 10
    });

    var measureTooltip = new mapboxgl.Popup({
      closeButton: false,
      anchor: 'bottom',
      offset: 10
    });

    map.on('load', function () {
      // 绘制中的图层
      map.addSource('geojson', {
        'type': 'geojson',
        'data': geojson
      });

      // Add styles to the map
      map.addLayer({
        id: 'measure-points',
        type: 'circle',
        source: 'geojson',
        paint: {
          'circle-radius': 5,
          'circle-color': '#000'
        },
        filter: ['in', '$type', 'Point']
      });
      map.addLayer({
        id: 'measure-lines',
        type: 'line',
        source: 'geojson',
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#000',
          'line-width': 2.5
        },
        filter: ['in', '$type', 'LineString']
      });

      // 绘制完成的图层
      map.addSource('old-geojson', {
        'type': 'geojson',
        'data': oldgeojson
      });

      // Add styles to the map
      map.addLayer({
        id: 'old-measure-points',
        type: 'circle',
        source: 'old-geojson',
        paint: {
          'circle-radius': 5,
          'circle-color': '#ffcc33'
        },
        filter: ['in', '$type', 'Point']
      });
      map.addLayer({
        id: 'old-measure-lines',
        type: 'line',
        source: 'old-geojson',
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#ffcc33',
          'line-width': 2.5
        },
        filter: ['in', '$type', 'LineString']
      });
    });

    map.on('click', function (e) {
      if (geojson.features.length > 1) geojson.features.pop();
      var point = getPointFeature(e.lngLat.lng, e.lngLat.lat);
      geojson.features.push(point);
      if (geojson.features.length == 1) {
        map.on('mousemove', onMouseMove);
      }
      if (geojson.features.length > 1) {
        var linestring = getLineFeature(geojson.features)
        geojson.features.push(linestring);
      }
      map.getSource('geojson').setData(geojson);
    });

    map.on('dblclick', function (e) {
      map.doubleClickZoom.disable();
      map.off('mousemove', onMouseMove);

      var linestring = geojson.features[geojson.features.length - 1];
      var value = turf.length(linestring).toLocaleString() + 'km';
      var lastPointCoord = geojson.features[geojson.features.length - 2].geometry.coordinates;
      var resultTooltip = new mapboxgl.Popup({
          closeButton: false,
          // 一定要设为false,否则默认点击地图关闭Popup
          closeOnClick: false,
          anchor: 'bottom',
          offset: 10
        })
        .setLngLat(lastPointCoord)
        .setHTML(`<div class = 'tooltip result'>${value}</div>`)
        .addTo(map);

      oldgeojson.features.push(...geojson.features);
      map.getSource('old-geojson').setData(oldgeojson);

      // 清空当前绘制的要素
      geojson.features = [];
      map.getSource('geojson').setData(geojson);
    });

    map.on('mousemove', onMouseMove);

    function onMouseMove(e) {
      if (geojson.features.length == 0) {
        helpTooltip.setLngLat(e.lngLat)
          .setHTML(`<div class = 'tooltip'>Click to start drawing</div>`)
          .addTo(map);
      }
      if (geojson.features.length > 1) {
        geojson.features.pop();
        geojson.features.pop();
      }
      if (geojson.features.length > 0) {
        helpTooltip.setLngLat(e.lngLat)
          .setHTML(`<div class = 'tooltip'>Click to continue drawing</div>`)
          .addTo(map);
        var point = getPointFeature(e.lngLat.lng, e.lngLat.lat);
        geojson.features.push(point);
        if (geojson.features.length > 1) {
          var linestring = getLineFeature(geojson.features)
          geojson.features.push(linestring);
          var value = turf.length(linestring).toLocaleString() + 'km';
          measureTooltip.setLngLat(e.lngLat)
            .setHTML(`<div class = 'tooltip'>${value}</div>`)
            .addTo(map);
        }
        map.getSource('geojson').setData(geojson);
      }
    }

    function getPointFeature(lng, lat) {
      var point = {
        'type': 'Feature',
        'geometry': {
          'type': 'Point',
          'coordinates': [lng, lat]
        },
        'properties': {
          'id': String(new Date().getTime())
        }
      };

      return point;
    }

    function getLineFeature(features) {
      var linestring = {
        'type': 'Feature',
        'geometry': {
          'type': 'LineString',
          'coordinates': []
        }
      };
      linestring.geometry.coordinates = features.map(
        function (point) {
          return point.geometry.coordinates;
        }
      );
      return linestring;
    }
  </script>

</body>

</html>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Mapbox-GL地图上线,可以使用Mapbox-GL的API方法来实现。下面是一种可能的方法: 首先,确保你已经引入了Mapbox-GL的库文件,并且创建了一个地图容器。然后,使用Mapbox-GL提供的`addLayer`方法来添加一个线条图层。 在`addLayer`方法中,你可以指定线条的样式和数据源。样式可以定义线条的颜色、宽度和其他属性,数据源可以定义线条的坐标点。 接下来,你可以使用`setData`方法将线条的坐标数据传递给数据源。坐标数据应该是一个包含经纬度信息的数组。 最后,将线条图层添加到地图中。你可以使用`addLayer`方法将图层添加到地图的指定位置。 下面是一个示例代码: ``` // 创建地图容器 var map = new mapboxgl.Map({ container: 'map-container', style: 'mapbox://styles/mapbox/streets-v11', }); // 添加线条图层 map.addLayer({ id: 'line-layer', type: 'line', source: { type: 'geojson', data: { type: 'Feature', geometry: { type: 'LineString', coordinates: [[lng1, lat1], [lng2, lat2], [lng3, lat3]] // 坐标点数组 } } }, paint: { 'line-color': '#ff0000', // 线条颜色 'line-width': 2 // 线条宽度 } }); // 设置线条图层的数据源 map.getSource('line-layer').setData({ type: 'Feature', geometry: { type: 'LineString', coordinates: [[lng1, lat1], [lng2, lat2], [lng3, lat3]] // 坐标点数组 } }); // 将线条图层添加到地图中 map.addLayer({ id: 'line-layer', type: 'line', source: 'line-source', paint: { 'line-color': '#ff0000', // 线条颜色 'line-width': 2 // 线条宽度 } }); ``` 以上就是使用Mapbox-GL线的方法。你可以根据自己的需求修改样式和坐标数据,以实现不同的效果。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Vue Mapbox-GL 在地图中增加图标、线条、标记点击弹窗、地图平移](https://blog.csdn.net/weixin_49032614/article/details/125545247)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值