通过读取表格数据转化成json数据,实现openlayer多段轨迹同时播放暂停

上效果图

东拼西凑 终于搞定了想要的效果

在这里插入图片描述

// 使用XLSX对xlsx数据进行解析
// xlsx容易报type的错
getExcelData() {
      const _this = this;
      axios
        .get("./../../static/data/json.xlsx", {
          responseType: "arraybuffer",
        })
        .then((res) => {
          let data = new Uint8Array(res.data);
          let wb = XLSX.read(data, { type: "array" });
          let sheets = wb.Sheets; // 获取文档数据
          _this.content = _this.transformSheets(sheets);
        })
        .catch((err) => {});
    },

    transformSheets(sheets) {
      let content1 = [];
      let tmplist = [];
      const _this = this;
      this.routeLayerList = [];
      for (let key in sheets) {
        //读出来的xlsx数据很难读,转换为json格式,参考https://github.com/SheetJS/js-xlsx#utility-functions
        tmplist.push(XLSX.utils.sheet_to_json(sheets[key]).length);
        content1.push(XLSX.utils.sheet_to_json(sheets[key]));
      }
      const pointList1 = this.alpha_sort(content1[0]);
      pointList1.forEach((item, i) => {
        let arr = this.objArrayduplicateRemoval(item.coords, "TIME");
        let obj = {
          GPSID: item.GPSID,
          coords: arr,
          visible: false,
          width: item.width,
        };
        this.doublePolylines.push(obj);// 轨迹线
        var coordList = arr.map((cood) => {
          return [parseFloat(cood.X), parseFloat(cood.Y)];
        });// 轨迹点
        this.route = new LineString(coordList);
        this.routeList.push(new LineString(coordList));
        var routeFeature = new Feature({
          type: "route",
          geometry: this.route,
        });
        routeFeature.setStyle(
          new Style({
            stroke: new Stroke({
              color: _this.colorList[i % 6],
              width: 6,
              strokeOpacity: 0.2,
            }),
            // zIndex: 99,
          })
        );
        // 添加轨迹
        this.routeLayerList.push(routeFeature);
      });
      this.addmarker();
    },
    objArrayduplicateRemoval(arr, key) {
      var obj = {};
      var results = [];
      for (var i = 0; i < arr.length; i++) {
        if (!obj[arr[i][key]]) {
          if (arr[i][key].length >= 11) {
            results.push(arr[i]);
            obj[arr[i][key]] = true;
          }
        }
      }
      results.sort(function (a, b) {
        return new Date(a.TIME) > new Date(b.TIME) ? 1 : -1;
      });
      return results;
    },
    alpha_sort(labels) {
      let alpha_dict = new Object();
      let factories = new Array();
      for (var i = 0; i < labels.length; i++) {
        let factory = labels[i];
        let GPSID = factory.GPSID;
        if (alpha_dict[GPSID] == undefined) {
          factories.push({
            GPSID: GPSID,
            coords: [factory],
          });
          alpha_dict[GPSID] = factories.length - 1;
        } else {
          factories[alpha_dict[GPSID]].coords.push(factory);
        }
      }
      return factories;
    },
    // 添加起终点的markers
    addmarker(param) {
      this.geoMarkerList = [];
      this.positionList = [];
      for (let i = 0; i < this.doublePolylines.length; i++) {
        const curLineCoords = this.doublePolylines[i].coords;
        const startPoint = [curLineCoords[0].X, curLineCoords[0].Y];
        const endPoint = [
          curLineCoords[curLineCoords.length - 1].X,
          curLineCoords[curLineCoords.length - 1].Y,
        ];
        console.log(startPoint);
        var startimg = this.newMarker(
          require("../assets/image/track_start.png"),
          startPoint
        );
        var endimg = this.newMarker(
          require("../assets/image/track_end.png"),
          endPoint
        );
        this.positionList.push(startimg.getGeometry().clone());
        if (param == 1) {
          this.addGeoMarker(i);
        } else {
          const _this = this;
          this.addmarkerLayer([_this.routeLayerList[i], startimg, endimg]);
        }
      }
    },
    // 添加第二个运动轨迹的小球marker
    addGeoMarker(i) {
      const geoMarker = new Feature({
        type: "geoMarker",
        geometry: this.positionList[i],
      });
      geoMarker.setStyle(this.styles.geoMarker);
      this.geoMarkerList.push(geoMarker);
      let vectorSource = new VectorSource({
        features: [this.geoMarkerList[i]],
      });
      const vectorLayer = new VectorLayer({
        source: vectorSource,
        zIndex: 99,
        name: "geoMarker",
        geoMarkerIndex: i,
      });
      this.vectorLayerList.push(vectorLayer);
      this.lastTimeList[i] = Date.now();
      this.vectorLayerList[i].on("postrender", this.moveFeature);
      this.map.addLayer(vectorLayer);
    },
    // 将起点终点marker 添加到地图上
    addmarkerLayer(feature) {
      let vectorSource = new VectorSource({
        features: feature,
      });
      const vectorLayer = new VectorLayer({
        source: vectorSource,
      });
      this.routeAndPointLayer.push(vectorLayer);
      this.map.addLayer(vectorLayer);
    },
    // 添加marker
    newMarker(url, point) {
      var markerIcon = new Feature({
        type: "icon",
        geometry: new Point(point),
      });
      markerIcon.setStyle(
        new Style({
          image: new Icon({
            size: [32, 32],
            src: url,
            offset: [0, 0],
          }),
        })
      );
      return markerIcon;
    },
    moveFeature(event) {
      const index = event.target.values_.geoMarkerIndex;
      const speed = 90;
      const time = event.frameState.time;
      const elapsedTime = time - this.lastTimeList[index];
      this.distanceList[index] =
        (this.distanceList[index] + (speed * elapsedTime) / 1e6) % 2;
      this.lastTimeList[index] = time;
      const currentCoordinate = this.routeList[index].getCoordinateAt(
        // 循环 来回播放
        // this.distance > 1 ? 2 - this.distance : this.distance
        // 单次
        this.distanceList[index] > 1 ? 1 : this.distanceList[index]
      );
      const _this = this;
      if (this.distanceList[index] > 1) {
        _this.geoMarkerList[index].setGeometry(_this.positionList[index]);
        this.vectorLayerList[index].un("postrender", this.moveFeature);
        this.btnText = "播放";
        this.isRePlay = true;
        this.distanceList[index] = 0;
        return;
      }
      this.positionList[index].setCoordinates(currentCoordinate);
      const vectorContext = getVectorContext(event);
      vectorContext.setStyle(this.styles.geoMarker);
      vectorContext.drawGeometry(this.positionList[index]);
      this.map.render();
    },
    // 删除轨迹
    deleteTrace(index) {
      console.log(this.routeAndPointLayer, index);
      this.map.removeLayer(this.routeAndPointLayer[index]);
      this.routeAndPointLayer.splice(index, 1);
      this.doublePolylines.splice(index, 1);
      if (this.doublePolylines.length == 0) {
        this.isShowReAdd = true;
      }
    },
    confirm() {},
    cancel() {},
    // 当数据清除完之后重新添加轨迹数据
    ReAdd() {
      this.addmarker();
    },
    handleVisibleChange(trace, index) {},
    // 播放/暂停轨迹
    btnClick() {
      if (this.btnText == "播放" || this.btnText == "继续") {
        this.btnText = "暂停";
        if (this.isRePlay) {
          this.isRePlay = false;
          this.vectorLayerList.forEach((layer) => {
            this.map.removeLayer(layer);
          });
          this.vectorLayerList = [];
          this.addmarker(1);
        } else {
          for (let i = 0; i < this.doublePolylines.length; i++) {
            this.addGeoMarker(i);
          }
        }
      } else if (this.btnText == "暂停") {
        this.btnText = "继续";
        for (let i = 0; i < this.doublePolylines.length; i++) {
          this.geoMarkerList[i].setGeometry(this.positionList[i]);
          this.vectorLayerList[i].un("postrender", this.moveFeature);
        }
      } else if (this.btnText == "继续") {
        this.btnText = "暂停";
        for (let i = 0; i < this.doublePolylines.length; i++) {
          this.geoMarkerList[i].setGeometry(this.positionList[i]);
          this.vectorLayerList[i].on("postrender", this.moveFeature);
        }
      }
   }

有不足之处还望各位大佬多多指点!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
格式的方法是什么? 可以使用 VBA 编写代码将 Excel 表格数据转换成 JSON 格式。具体操作步骤见下文: 1. 对 Excel 表格中的数据进行读取; 2. 将读取数据转换成 JSON 格式的字符串; 3. 将字符串写到输出文件中。 你可以参考以下代码: Sub Excel2JSON() Dim objWorksheet As Worksheet Set objWorksheet = ThisWorkbook.Worksheets("Sheet1") ' Sheet1 为要操作的表格名 Dim intLastRow As Long intLastRow = objWorksheet.Cells(Rows.Count, "A").End(xlUp).Row ' 获取表格中最后一行的行号 Dim intLastCol As Long intLastCol = objWorksheet.Cells(1, Columns.Count).End(xlToLeft).Column ' 获取表格中最后一列的列号 Dim dictData As Object Set dictData = CreateObject("Scripting.Dictionary") Dim intRow As Long Dim intCol As Long For intRow = 2 To intLastRow ' 从第 2 行开始遍历 Dim dictRowData As Object Set dictRowData = CreateObject("Scripting.Dictionary") For intCol = 1 To intLastCol dictRowData(objWorksheet.Cells(1, intCol).Value) = objWorksheet.Cells(intRow, intCol).Value ' 获取每一行数据 Next intCol dictData(intRow - 1) = dictRowData ' 将每一行数据存入字典中 Next intRow Dim objJSON As Object Set objJSON = CreateObject("Scripting.Dictionary") objJSON.Add "data", dictData ' 将数据存入 JSON Dim strOutput As String strOutput = JsonConverter.ConvertToJson(objJSON) ' 将 JSON 转换成字符串 Debug.Print strOutput ' 输出字符串到控制台 End Sub 注意:需要先安装 VBA-JSON 模块才能使用 JsonConverter。可以在 https://github.com/VBA-tools/VBA-JSON 下载最新版。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cesium小菜王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值