2025-03-28

<template>
<div id="container" class="map"></div>

<div class="controls">
<el-button type="primary" @click="togglePlayback" :disabled="!hasValidTrack">
{{ isPlaying ? '暂停' : '开始' }}
</el-button>
<el-slider
v-model="playbackProgress"
:max="maxProgress"
:min="0"
:step="1"
:disabled="!hasValidTrack"
@change="onSliderChange"
style="width: 300px"
></el-slider>
<el-select
v-model="playbackSpeed"
placeholder="倍速"
style="width: 100px"
:disabled="!hasValidTrack"
>
<el-option label="0.5x" :value="0.5"></el-option>
<el-option label="1x" :value="1"></el-option>
<el-option label="1.5x" :value="1.5"></el-option>
<el-option label="2x" :value="2"></el-option>
<el-option label="3x" :value="3"></el-option>
<el-option label="4x" :value="4"></el-option>
<el-option label="5x" :value="5"></el-option>
</el-select>
</div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch, computed } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { thenrackStore } from '@/store/track'

const userTrackStore = thenrackStore()

// 地图变量
let map
let polyline
let carMarker = null
let startMarker = null
let endMarker = null
let moveTimer = null

// 响应式变量
const lineArr = ref([])
const playbackProgress = ref(0)
const playbackSpeed = ref(1)
const isPlaying = ref(false)

// 计算属性
const hasValidTrack = computed(() => lineArr.value.length >= 2)
const maxProgress = computed(() => Math.max(0, lineArr.value.length - 1))

// 初始化地图
const initMap = () => {
AMapLoader.load({
key: 'f6f57587741cda999c3968cfcf17a552',
version: '2.0',
plugins: ['AMap.Polyline', 'AMap.Marker', 'AMap.GraspRoad'], // 加载 GraspRoad 插件
})
.then((AMapInstance) => {
map = new AMapInstance.Map('container', {
viewMode: '3D',
zoom: 15,
center: [116.397428, 39.90923],
})

  if (lineArr.value.length >= 2) {
    correctTrajectory(lineArr.value) // 调用轨迹纠偏
  }
})
.catch((e) => {
  console.error('地图加载失败:', e)
})

}

// 验证坐标有效性
const isValidPosition = (position) => {
return (
position &&
Array.isArray(position) &&
position.length === 2 &&
!isNaN(position[0]) &&
!isNaN(position[1])
)
}

// 轨迹纠偏方法
const correctTrajectory = (originPath) => {
console.log('原始轨迹:', originPath)
if (!originPath || originPath.length < 2) {
console.error('轨迹数据无效,无法进行纠偏')
return
}
// 验证每个点的格式
const isValidPath = originPath.every(
(point) =>
Array.isArray(point) &&
point.length === 2 &&
typeof point[0] === 'number' &&
typeof point[1] === 'number' &&
point[0] >= -180 &&
point[0] <= 180 &&
point[1] >= -90 &&
point[1] <= 90
);

if (!isValidPath) {
console.error('轨迹点格式无效,请检查数据结构');
return;
}
console.log('isValidPath', isValidPath)

AMap.plugin('AMap.GraspRoad', function () {
const grasp = new AMap.GraspRoad()

console.log(grasp,'graspgraspgraspgraspgrasp')
grasp.driving(originPath, function (error, result) {
  console.log(error, result,'originPath')
  if (!error && result.data) {
    const newPath = result.data.points // 纠偏后的轨迹
    const distance = result.data.distance // 纠偏后的里程
    console.log('纠偏后的轨迹:', newPath)
    console.log('纠偏后的里程:', distance)

    // 更新轨迹数据
    lineArr.value = newPath.map((point) => [point.longitude, point.latitude])

    // 创建地图元素
    createMapElements()
  } else {
    console.error('轨迹纠偏失败:', error || '未知错误')
  }
})

})
}

// 创建地图元素
const createMapElements = () => {
if (!map || lineArr.value.length < 2) return

if (polyline) polyline.setMap(null)
if (startMarker) startMarker.setMap(null)
if (endMarker) endMarker.setMap(null)
if (carMarker) carMarker.setMap(null)

polyline = new AMap.Polyline({
path: lineArr.value,
showDir: true,
strokeColor: '#28F',
strokeWeight: 6,
map: map,
})

startMarker = new AMap.Marker({
position: lineArr.value[0],
icon: new AMap.Icon({
size: new AMap.Size(25, 34),
image: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
imageSize: new AMap.Size(25, 34),
}),
title: '起点',
map: map,
offset: new AMap.Pixel(-12, -34),
})

const endPoint = lineArr.value[lineArr.value.length - 1]
endMarker = new AMap.Marker({
position: endPoint,
icon: new AMap.Icon({
size: new AMap.Size(25, 34),
image: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
imageSize: new AMap.Size(25, 34),
}),
title: '终点',
map: map,
offset: new AMap.Pixel(-12, -34),
})

initCarMarker()
map.setFitView([polyline])
}

// 初始化车辆标记点
const initCarMarker = () => {
if (!lineArr.value.length) return

const iconUrl = 'http://8.133.255.205:3080/img/vehicle/1.png'
carMarker = new AMap.Marker({
position: lineArr.value[0],
icon: new AMap.Icon({
size: new AMap.Size(36, 70),
image: iconUrl,
imageSize: new AMap.Size(19, 39),
}),
offset: new AMap.Pixel(-16, -16),
autoRotation: true,
map: map,
})
}

// 切换轨迹回放状态
const togglePlayback = () => {
if (!hasValidTrack.value) return
isPlaying.value ? pausePlayback() : startPlayback()
}

// 开始轨迹回放
const startPlayback = () => {
if (!hasValidTrack.value || !carMarker) return

if (playbackProgress.value >= lineArr.value.length - 1) {
playbackProgress.value = 0
carMarker.setPosition(lineArr.value[0])
}

let index = playbackProgress.value
let nextIndex = Math.min(index + 1, lineArr.value.length - 1)
let step = 0
const totalSteps = 60

if (moveTimer) clearInterval(moveTimer)
isPlaying.value = true

moveTimer = setInterval(() => {
if (index >= lineArr.value.length - 1) {
clearInterval(moveTimer)
isPlaying.value = false
return
}

const currentPos = [
  lineArr.value[index][0] +
    (lineArr.value[nextIndex][0] - lineArr.value[index][0]) * (step / totalSteps),
  lineArr.value[index][1] +
    (lineArr.value[nextIndex][1] - lineArr.value[index][1]) * (step / totalSteps),
]

if (isValidPosition(currentPos)) {
  carMarker.setPosition(currentPos)
}

step++

if (step > totalSteps) {
  step = 0
  index++
  nextIndex = Math.min(index + 1, lineArr.value.length - 1)
  playbackProgress.value = index
}

}, 16 / playbackSpeed.value)
}

// 暂停轨迹回放
const pausePlayback = () => {
if (moveTimer) {
clearInterval(moveTimer)
moveTimer = null
isPlaying.value = false
}
}

// 进度条改变事件
const onSliderChange = (value) => {
if (!hasValidTrack.value || !carMarker || value >= lineArr.value.length) return

const position = lineArr.value[value]
if (isValidPosition(position)) {
carMarker.setPosition(position)
}
}

watch(
() => userTrackStore.devicelTrackData,
(newVal) => {
if (!newVal || newVal.length < 2) {
lineArr.value = []
playbackProgress.value = 0
isPlaying.value = false
if (moveTimer) clearInterval(moveTimer)
return
}
const originPath = userTrackStore.devicelTrackData.map((point) => [point.lng, point.lat])
console.log(userTrackStore.devicelTrackData,'userTrackStore.devicelTrackData')
correctTrajectory(originPath) // 调用轨迹纠偏
},
{ deep: true },
)

onMounted(initMap)

onUnmounted(() => {
if (map) map.destroy()
if (moveTimer) clearInterval(moveTimer)
})
</script>

<style scoped>
.map {
width: 100%;
height: 80%;
}

container {

width: 100%;
height: calc(100% - 10px);
}

.controls {
position: absolute;
top: 85%;
left: 50%;
transform: translate(-50%, 0);
z-index: 999;
background: rgba(255, 255, 255, 0.8);
padding: 10px;
border-radius: 4px;
display: flex;
gap: 20px;
align-items: center;
}
</style>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容