MapBox添加带箭头的轨迹线

效果:
在这里插入图片描述

// 轨迹线
export const MAP_PATH_LINE = (values, layerId) => {
  // 箭头-右
  var svgXML = `<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"> 
         <path d="M529.6128 512L239.9232 222.4128 384.7168 77.5168 819.2 512 384.7168 946.4832 239.9232 801.5872z" p-id="9085" fill="#ffffff"></path> 
     </svg>
     `;
  //给图片对象写入base64编码的svg流
  var svgBase64 = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgXML)));

  let arrowIcon = new Image(20, 20);

  arrowIcon.src = svgBase64;

  arrowIcon.onload = function () {
    map.addImage('arrowIcon', arrowIcon);
    setRouteData();
    // map.loadImage('./car.png', function (error, carIcon) {
    //   if (carIcon) {
    //     map.addImage('carIcon', carIcon);
    //     setRouteData();
    //   }
    // });
  };

  var isPlay = true;
  var counter = 0;
  var steps = 0;
  let aLength = 0;
  let newRouteGeoJson;
  var routeGeoJson = values;

  var realRouteGeoJson = {
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: [],
        },
      },
    ],
  };

  var animatePointGeoJson = {
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        properties: {},
        geometry: {
          type: 'Point',
          coordinates: [],
        },
      },
    ],
  };

  // 获取轨迹边界
  var bbox = turf.bbox(routeGeoJson);

  map.fitBounds(
    [
      [Number(bbox[0]), Number(bbox[1])],
      [Number(bbox[2]), Number(bbox[3])],
    ],
    {
      padding: { top: 100, bottom: 100, left: 100, right: 100 },
      maxZoom: 16,
    },
  );

  // 获取轨迹数据
  function setRouteData() {
    animatePointGeoJson.features[0].geometry.coordinates = routeGeoJson.features[0].geometry.coordinates[0];
    aLength = routeGeoJson.features[0].geometry.coordinates.length;
    newRouteGeoJson = resetRoute(routeGeoJson.features[0], 1000, 'kilometers');
    steps = newRouteGeoJson.geometry.coordinates.length;

    addRouteBboxLayer(); // 添加轨迹边界图层
    addRoutelayer(); // 添加轨迹线图层
    // addRealRouteSource(); // 添加实时轨迹线图层
    addArrowlayer(); // 添加箭头图层
    // addAnimatePointSource(); // 添加动态点图层
  }

  // 添加轨迹边界图层
  function addRouteBboxLayer() {
    map.addLayer({
      id: 'routeBboxLayer',
      type: 'line',
      source: {
        type: 'geojson',
        data: turf.bboxPolygon(bbox),
      },
      paint: {
        'line-color': '#fbc219',
        'line-width': 3,
        'line-dasharray': [1, 1],
        'line-offset': -10,
      },
    });
  }

  // 添加轨迹线图层
  function addRoutelayer() {
    map.addLayer({
      id: 'routeLayer',
      type: 'line',
      source: {
        type: 'geojson',
        lineMetrics: true,
        data: routeGeoJson,
      },
      paint: {
        'line-width': 10,
        'line-opacity': 1,
        'line-color': '#009EFF',
      },
    });
  }

  // 添加实时轨迹线
  function addRealRouteSource() {
    map.addLayer({
      id: 'realRouteLayer',
      type: 'line',
      source: {
        type: 'geojson',
        lineMetrics: true,
        data: realRouteGeoJson,
      },
      paint: {
        'line-width': 10,
        'line-opacity': 1,
        'line-color': '#FF9900',
      },
    });
  }

  // 添加箭头图层
  function addArrowlayer() {
    map.addLayer({
      id: 'arrowLayer',
      type: 'symbol',
      source: {
        type: 'geojson',
        data: routeGeoJson, //轨迹geojson格式数据
      },
      layout: {
        'symbol-placement': 'line',
        'symbol-spacing': 50, // 图标间隔,默认为250
        'icon-image': 'arrowIcon', //箭头图标
        'icon-size': 0.5,
      },
    });
  }

  // 添加动态点图层
  function addAnimatePointSource() {
    map.addLayer({
      id: 'animatePointLayer',
      type: 'symbol',
      source: {
        type: 'geojson',
        data: animatePointGeoJson,
      },
      layout: {
        'icon-image': 'carIcon',
        'icon-size': 0.5,
        'icon-rotate': ['get', 'bearing'],
        'icon-rotation-alignment': 'map',
        'icon-allow-overlap': true,
        'icon-ignore-placement': true,
      },
    });

    animate();
  }

  function animate() {
    if (counter >= steps) {
      return;
    }

    var startPnt, endPnt;

    if (counter == 0) {
      realRouteGeoJson.features[0].geometry.coordinates = [];
      startPnt = newRouteGeoJson.geometry.coordinates[counter];
      endPnt = newRouteGeoJson.geometry.coordinates[counter + 1];
    } else if (counter !== 0) {
      startPnt = newRouteGeoJson.geometry.coordinates[counter - 1];
      endPnt = newRouteGeoJson.geometry.coordinates[counter];
    }

    animatePointGeoJson.features[0].properties.bearing = turf.bearing(turf.point(startPnt), turf.point(endPnt)) - 90;
    animatePointGeoJson.features[0].geometry.coordinates = newRouteGeoJson.geometry.coordinates[counter];
    realRouteGeoJson.features[0].geometry.coordinates.push(animatePointGeoJson.features[0].geometry.coordinates);

    map.getSource('animatePointLayer').setData(animatePointGeoJson);
    map.getSource('realRouteLayer').setData(realRouteGeoJson);

    if (isPlay) {
      requestAnimationFrame(animate);
    }

    counter = counter + 1;
  }

  function resetRoute(route, nstep, units) {
    var newroute = {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [],
      },
    };
    var lineDistance = turf.lineDistance(route);
    var nDistance = lineDistance / nstep;

    for (let i = 0; i < aLength - 1; i++) {
      var from = turf.point(route.geometry.coordinates[i]);
      var to = turf.point(route.geometry.coordinates[i + 1]);
      let lDistance = turf.distance(from, to, {
        units: units,
      });

      if (i == 0) {
        newroute.geometry.coordinates.push(route.geometry.coordinates[0]);
      }

      if (lDistance > nDistance) {
        let rings = lineMore(from, to, lDistance, nDistance, units);

        newroute.geometry.coordinates = newroute.geometry.coordinates.concat(rings);
      } else {
        newroute.geometry.coordinates.push(route.geometry.coordinates[i + 1]);
      }
    }

    return newroute;
  }

  function lineMore(from, to, distance, splitLength, units) {
    var step = parseInt(distance / splitLength);
    var leftLength = distance - step * splitLength;
    var rings = [];
    var route = turf.lineString([from.geometry.coordinates, to.geometry.coordinates]);

    for (let i = 1; i <= step; i++) {
      let nlength = i * splitLength;
      let pnt = turf.along(route, nlength, {
        units: units,
      });

      rings.push(pnt.geometry.coordinates);
    }

    if (leftLength > 0) {
      rings.push(to.geometry.coordinates);
    }

    return rings;
  }
};

清除数据代码

// 清除轨迹
export const ClearTrackMap = () => {
  if (map?.hasImage('arrowIcon')) map?.removeImage('arrowIcon');
  if (map?.hasImage('carIcon')) map?.removeImage('carIcon');

  if (map.getLayer('routeBboxLayer')) map.removeLayer('routeBboxLayer');
  if (map.getSource('routeBboxLayer')) map.removeSource('routeBboxLayer');

  if (map.getLayer('routeLayer')) map.removeLayer('routeLayer');
  if (map.getSource('routeLayer')) map.removeSource('routeLayer');
  if (map.getLayer('realRouteLayer')) map.removeLayer('realRouteLayer');
  if (map.getSource('realRouteLayer')) map.removeSource('realRouteLayer');
  if (map.getLayer('arrowLayer')) map.removeLayer('arrowLayer');
  if (map.getSource('arrowLayer')) map.removeSource('arrowLayer');
  if (map.getLayer('animatePointLayer')) map.removeLayer('animatePointLayer');
  if (map.getSource('animatePointLayer')) map.removeSource('animatePointLayer');

  REMOVE_LAYER('vectorDataID');
  REMOVE_LAYER(`feature_0.1`);
};
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
mapboxgl是一个用于构建交互式地图的开源JavaScript库。要绘制轨迹线,你可以使用mapboxgl的`LineString`和`GeoJSONSource`类。 首先,你需要引入mapboxgl库,并创建一个地图容器。然后,使用`LineString`类来创建一个表示轨迹线的几何对象。你可以定义轨迹线的坐标点,以及其他属性如颜色、宽度等。 接下来,创建一个`GeoJSONSource`实例,并将轨迹线添加到该源中。然后,将该源添加到地图中。 以下是一个简单的示例代码: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Mapbox GL JS - Display a line</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <script src="https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.js"></script> <link href="https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.css" rel="stylesheet" /> <style> body { margin: 0; padding: 0; } #map { position: absolute; top: 0; bottom: 0; width: 100%; } </style> </head> <body> <div id="map"></div> <script> mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'; // 替换为你的Mapbox Access Token var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [-74.5, 40], // 初始地图中心点坐标 zoom: 9 // 初始缩放级别 }); var lineString = { type: 'Feature', geometry: { type: 'LineString', coordinates: [ [-74.5, 40], // 轨迹线坐标点1 [-74.3, 39.8], // 轨迹线坐标点2 [-74.1, 39.6] // 轨迹线坐标点3 ] } }; map.on('load', function () { map.addSource('line', { type: 'geojson', data: { type: 'FeatureCollection', features: [lineString] } }); map.addLayer({ id: 'line', type: 'line', source: 'line', layout: { 'line-join': 'round', 'line-cap': 'round' }, paint: { 'line-color': '#888', 'line-width': 8 } }); }); </script> </body> </html> ``` 在上述代码中,你需要将`YOUR_ACCESS_TOKEN`替换为你的Mapbox Access Token。此外,你还可以根据需要修改地图样式、初始中心点和缩放级别、轨迹线的坐标点、颜色和宽度等参数。 通过以上步骤,你就可以在地图上绘制轨迹线了。希望对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值