wanglizhong
2025-05-03 a296c6bfa83cd0a4bbc92d93c015a010248e8455
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="车牌号" prop="vehicleNo">
        <el-input
          v-model="queryParams.vehicleNo"
          placeholder="请输入车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
 
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>轨迹列表</span>
          </div>
          <el-table
            v-loading="loading"
            :data="gpsList"
            height="600"
            @row-click="handleRowClick"
          >
            <el-table-column label="时间" align="center" prop="collectTime" />
            <el-table-column label="速度(km/h)" align="center" prop="speed" />
            
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="18">
        <div id="mapContainer" style="height: 600px"></div>
        <div class="track-controls">
          <el-button-group>
            <el-button
              size="small"
              @click="showPreviousSegment"
              :disabled="segmentIndex === 0"
            >
              <i class="el-icon-arrow-left"></i> 上一段
            </el-button>
            <el-button
              size="small"
              @click="showNextSegment"
              :disabled="(segmentIndex + 1) * segmentSize >= gpsList.length"
            >
              下一段 <i class="el-icon-arrow-right"></i>
            </el-button>
          </el-button-group>
          <el-button-group style="margin-left: 10px">
            <el-button
              size="small"
              type="primary"
              @click="startPlayback"
              :disabled="isPlaying"
            >
              <i class="el-icon-video-play"></i> 开始回放
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="stopPlayback"
              :disabled="!isPlaying"
            >
              <i class="el-icon-video-pause"></i> 停止回放
            </el-button>
          </el-button-group>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
 
<script>
import { listGps } from "@/api/system/gps";
 
export default {
  name: "GpsMap",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // GPS数据表格数据
      gpsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        vehicleNo: undefined,
        orderByColumn: "collect_time",
        isAsc: "desc",
      },
      // 地图对象
      map: null,
      // 轨迹线
      polyline: null,
      // 标记点数组
      markers: [],
      // 轨迹分段显示
      segmentIndex: 0,
      segmentSize: 50, // 每段显示的点数
      // 轨迹回放
      isPlaying: false,
      playInterval: null,
      smoothFactor: 0.3, // 平滑因子,值越大越平滑
      minDistance: 50, // 最小插值距离(米)
 
      currentPlayIndex: 0,
      playSpeed: 1000, // 回放速度(毫秒)
      currentMarker: null,
    };
  },
  created() {
    // 获取URL参数中的车牌号
    const vehicleNo = this.$route.query.vehicleNo;
    if (vehicleNo) {
      this.queryParams.vehicleNo = vehicleNo;
    }
    this.getList();
  },
  mounted() {
    // 动态加载百度地图API
    this.loadBMapScript().then(() => {
      this.initMap();
    });
  },
  methods: {
    /** 加载百度地图API */
    loadBMapScript() {
      return new Promise((resolve, reject) => {
        if (window.BMap) {
          resolve(window.BMap);
          return;
        }
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.src =
          "https://api.map.baidu.com/api?v=3.0&ak=n5z5pKfAnaP3fYMR4RJOAQsR1wQ2avAn&callback=initBMap";
        script.onerror = reject;
        document.head.appendChild(script);
        window.initBMap = () => {
          // 加载坐标转换库
          const convertorScript = document.createElement("script");
          convertorScript.type = "text/javascript";
          convertorScript.src =
            "https://api.map.baidu.com/getscript?v=3.0&ak=n5z5pKfAnaP3fYMR4RJOAQsR1wQ2avAn&services=&t=20230101100000";
          convertorScript.onload = () => {
            // 加载坐标转换工具
            const toolsScript = document.createElement("script");
            toolsScript.type = "text/javascript";
            toolsScript.src =
              "https://api.map.baidu.com/library/Convertor/1.4/src/Convertor_min.js";
            toolsScript.onload = () => {
              resolve(window.BMap);
            };
            document.head.appendChild(toolsScript);
          };
          document.head.appendChild(convertorScript);
        };
      });
    },
    /** 查询GPS列表 */
    getList() {
      this.loading = true;
      listGps(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.gpsList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.drawTrack();
        }
      );
    },
    async translatePoints(points) {
      // 将WGS84坐标转换为百度坐标
      var translatePoints = [];
      return new Promise((resolve, reject) => {
        const convertor = new BMap.Convertor();
        convertor.translate(points, 1, 5, (data) => {
          if (data.status === 0) {
            translatePoints = data.points;
            resolve(translatePoints);
          }
        });
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 初始化地图 */
    initMap() {
      // 创建地图实例
      this.map = new BMap.Map("mapContainer");
      // 设置地图中心点和缩放级别
      this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
      // 启用滚轮放大缩小
      this.map.enableScrollWheelZoom();
    },
     /** 计算两点之间的距离(米) */
     getDistance(point1, point2) {
        return this.map.getDistance(point1, point2);
      },
      /** 计算两点之间的角度 */
      getAngle(point1, point2) {
        const dx = point2.lng - point1.lng;
        const dy = point2.lat - point1.lat;
        return Math.atan2(dy, dx) * 180 / Math.PI;
      },
 
     /** 在两点之间插入平滑点 */
     getSmoothPoints(point1, point2) {
        const distance = this.getDistance(point1, point2);
        if (distance < this.minDistance) {
          return [point1, point2];
        }
        
        const angle = this.getAngle(point1, point2);
        const midPoint = new BMap.Point(
          (point1.lng + point2.lng) / 2,
          (point1.lat + point2.lat) / 2
        );
        
        // 计算控制点
        const controlPoint = new BMap.Point(
          midPoint.lng + this.smoothFactor * distance * Math.cos((angle + 90) * Math.PI / 180),
          midPoint.lat + this.smoothFactor * distance * Math.sin((angle + 90) * Math.PI / 180)
        );
        
        // 使用二次贝塞尔曲线生成平滑点
        const points = [];
        for (let t = 0; t <= 1; t += 0.1) {
          const x = Math.pow(1 - t, 2) * point1.lng + 2 * (1 - t) * t * controlPoint.lng + Math.pow(t, 2) * point2.lng;
          const y = Math.pow(1 - t, 2) * point1.lat + 2 * (1 - t) * t * controlPoint.lat + Math.pow(t, 2) * point2.lat;
          points.push(new BMap.Point(x, y));
        }
        return points;
      },
 
    /** 绘制轨迹 */
    async drawTrack() {
      // 清除之前的轨迹
      if (this.polyline) {
        this.map.removeOverlay(this.polyline);
      }
      this.markers.forEach((marker) => {
        this.map.removeOverlay(marker);
      });
      this.markers = [];
 
      if (this.gpsList.length === 0) {
        return;
      }
 
      // 按时间排序
      this.gpsList.sort((a, b) => {
        return new Date(a.collectTime) - new Date(b.collectTime);
      });
 
      // 计算当前段落的起始和结束索引
      const startIndex = this.segmentIndex * this.segmentSize;
      const endIndex = Math.min(
        startIndex + this.segmentSize,
        this.gpsList.length
      );
      const currentSegment = this.gpsList.slice(startIndex, endIndex);
 
      //先获得所有坐标数组
      const originPoints = currentSegment.map(
        (item) => new BMap.Point(item.longitude, item.latitude)
      );
    
      this.gpsList.sort((a, b) => {
        return new Date(b.collectTime) - new Date(a.collectTime);
      }).forEach(item => {
       item.speed=item.speed/1000;
      });
      //批量转换坐标
      var translatePoints = await this.translatePoints(originPoints);
 
      // 创建轨迹点数组
      const points = translatePoints;
      translatePoints.forEach((item, index) => {
        const bdPoint = item;
 
        // 只在起点和终点创建标记
        if (index === 0 || index === translatePoints.length - 1) {
          let marker;
          let direction=currentSegment[index].direction;
          if (index === 0) {
            // 起点显示"起"字
            const label = new BMap.Label("起", {
              offset: new BMap.Size(0, 0),
              position: bdPoint,
            });
            label.setStyle({
              color: "white",
              fontSize: "12px",
              backgroundColor: "#3388ff",
              border: "none",
              padding: "2px 6px",
              borderRadius: "3px",
            });
            marker = new BMap.Marker(bdPoint,{rotation:direction});
            marker.setLabel(label);
          } else {
            // 终点显示车辆图标
           
            const myIcon = new BMap.Icon(
              "/car_blue.png",
              new BMap.Size(20, 20),
              {
                imageSize: new BMap.Size(20, 20),
                anchor: new BMap.Size(10, 10),
              }
            );
            marker = new BMap.Marker(bdPoint, {
              icon: myIcon,
              rotation: direction,
            });
          }
 
          // 获取地址信息
          const geoc = new BMap.Geocoder();
          geoc.getLocation(bdPoint, (rs) => {
            const addComp = rs.addressComponents;
            const address =
              addComp.province +
              addComp.city +
              addComp.district +
              addComp.street +
              addComp.streetNumber;
 
            // 添加信息窗口
            const infoWindow = new BMap.InfoWindow(
              `时间:${item.collectTime}<br/>速度:${
                item.speed
              }km/h<br/>方向:${item.direction}°<br/>地址:${address}`
            );
            marker.addEventListener("click", () => {
              this.map.openInfoWindow(infoWindow, bdPoint);
            });
          });
 
          this.map.addOverlay(marker);
          this.markers.push(marker);
        }
        // const smoothPoints = [];
        // for (let i = 0; i < points.length - 1; i++) {
        //   const segmentPoints = this.getSmoothPoints(points[i], points[i + 1]);
        //   smoothPoints.push(...segmentPoints);
        // }
        // smoothPoints.push(points[points.length - 1]);
 
        // 如果是最后一个点,绘制轨迹线
        if (index === currentSegment.length - 1) {
          // 创建轨迹线
          this.polyline = new BMap.Polyline(points, {
            strokeColor: "#3388ff",
            strokeWeight: 5,
            strokeOpacity: 0.8,
            strokeStyle: "solid",
          });
          this.map.addOverlay(this.polyline);
 
          // 调整地图视野以显示完整轨迹
          this.map.setViewport(points);
        }
      });
    },
    /** 点击表格行 */
    handleRowClick(row) {
      const point = new BMap.Point(row.longitude, row.latitude);
      const convertor = new BMap.Convertor();
      convertor.translate([point], 1, 5, (data) => {
        if (data.status === 0) {
          // 移除之前的标记点
          if (this.currentMarker) {
            this.map.removeOverlay(this.currentMarker);
          }
          
          // 创建新的标记点
          const myIcon = new BMap.Icon(
            "/car_blue.png",
            new BMap.Size(20, 20),
            {
              imageSize: new BMap.Size(20, 20),
              anchor: new BMap.Size(10, 10),
            }
          );
          const marker = new BMap.Marker(data.points[0], {
            icon: myIcon,
            rotation: row.direction,
          });
          
          // 显示车牌
          const label = new BMap.Label(row.vehicleNo, {
            offset: new BMap.Size(0, -25), // 向上偏移25像素
            position: data.points[0],
          });
          label.setStyle({
            color: "white",
            fontSize: "12px",
            backgroundColor: "#3388ff",
            border: "none",
            padding: "2px 6px",
            borderRadius: "3px",
            whiteSpace: "nowrap", // 防止文字换行
          });
          marker.setLabel(label);
          
          // 添加信息窗口
          const infoWindow = new BMap.InfoWindow(
            `时间:${row.collectTime}<br/>速度:${row.speed}km/h<br/>方向:${row.direction}°<br/>地址:${row.address}`
          );
          marker.addEventListener("click", () => {
            this.map.openInfoWindow(infoWindow, data.points[0]);
          });
          
          // 保存当前标记点引用
          this.currentMarker = marker;
          
          // 添加到地图并居中显示
          this.map.addOverlay(marker);
          this.map.setCenter(data.points[0]);
          this.map.setZoom(15);
        }
      });
    },
    /** 显示上一段轨迹 */
    showPreviousSegment() {
      if (this.segmentIndex > 0) {
        this.segmentIndex--;
        this.drawTrack();
      }
    },
    /** 显示下一段轨迹 */
    showNextSegment() {
      if ((this.segmentIndex + 1) * this.segmentSize < this.gpsList.length) {
        this.segmentIndex++;
        this.drawTrack();
      }
    },
    /** 开始轨迹回放 */
    startPlayback() {
      if (this.isPlaying) return;
      this.isPlaying = true;
      this.currentPlayIndex = 0;
      this.playInterval = setInterval(() => {
        if (this.currentPlayIndex < this.gpsList.length) {
          const item = this.gpsList[this.currentPlayIndex];
          const point = new BMap.Point(item.longitude, item.latitude);
          const convertor = new BMap.Convertor();
          convertor.translate([point], 1, 5, (data) => {
            if (data.status === 0) {
              const bdPoint = data.points[0];
              this.map.setCenter(bdPoint);
              this.map.setZoom(15);
            }
          });
          this.currentPlayIndex++;
        } else {
          this.stopPlayback();
        }
      }, this.playSpeed);
    },
    /** 停止轨迹回放 */
    stopPlayback() {
      if (this.playInterval) {
        clearInterval(this.playInterval);
        this.playInterval = null;
      }
      this.isPlaying = false;
    },
  },
  beforeDestroy() {
    this.stopPlayback();
  },
};
</script>
 
<style scoped>
.box-card {
  margin-bottom: 20px;
}
.track-controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>