四十二、openlayers官网示例Flight Animation扩展——在地图上绘制飞机航线、飞机随航线飞行效果

作者 : admin 本文共1535个字,预计阅读时间需要4分钟 发布时间: 2024-06-8 共3人阅读

四十二、openlayers官网示例Flight Animation扩展——在地图上绘制飞机航线、飞机随航线飞行效果插图 

上篇在地图上绘制了动态的飞机航线,于是我想着,能不能加个飞机的图标跟着航线飞行。

在iconfont上下载一个飞机的svg图形,放在public的data/icons下面 

因为图标需要随着航线的方向飞行,需要根据航线调整角度,因此在加载数据源的时候需要计算一下角度,绑在每个feature上。

//计算角度
const rotation = calculateRotation(from, to);
 features.push(
     new Feature({
          geometry: line,
          finished: false,
          rotation: rotation,
      })
   );
  function calculateRotation(from, to) {
      const dx = to[0] - from[0];
      const dy = to[1] - from[1];
      return Math.atan2(dy, dx);
   }

在航线绘制完成之后,添加一个飞机动画开始执行的标识flight,给feature设置一个初始的index值

if (elapsedPoints >= coords.length) {
      feature.set("finished", true);
      feature.set("flight", true);
      feature.set("index", 0);
 }

animateFlights会一直执行,所以我们利用这个特点来绘制循环的动画。绘制线的思路是取坐标数组的第0个到第n个,每毫秒绘制不同的线。绘制点的思路则是直接取第n个点,每毫秒绘制不同的点,并且在n大于等于坐标数组之后又让n重新等于0,以此来实现循环的动画。

 if (feature.get("flight")) {
          const frameState = event.frameState;
          const coords = feature.getGeometry().getCoordinates();
          let index = feature.get("index");
          index += step;
          if (index >= coords.length - 1) {
            index = 0;
          }
          if (index < 0) {
            index = 0;
          }
          feature.set("index", index);
          style.getImage().setRotation(feature.get("rotation"));
          vectorContext.setStyle(style);
          const currentPoint = new Point(coords[Math.floor(index)]);

          // 在当前和最近相邻的包裹世界中需要动画
          const worldWidth = getWidth(
            map.getView().getProjection().getExtent()
          );
          const offset = Math.floor(map.getView().getCenter()[0] / worldWidth);
          //直接用矢量上下文绘制线条
          //在平铺地图上绘制线段时,需要考虑地图的无限水平滚动特性。通过平移和多次绘制线段,确保即使用户滚动地图,线段也能正确显示在地图的两端。这个方法处理了跨越地图边界的线段,避免了图形被截断的问题。
          currentPoint.translate(offset * worldWidth, 0);
          vectorContext.drawGeometry(currentPoint);
          currentPoint.translate(worldWidth, 0);
          vectorContext.drawGeometry(currentPoint);
        }

完整代码:


  
    

External map

#map { width: 100%; height: 500px; } .box { height: 100%; }

本站无任何商业行为
个人在线分享 » 四十二、openlayers官网示例Flight Animation扩展——在地图上绘制飞机航线、飞机随航线飞行效果
E-->