<script lang="ts" setup>
/* 地图容器 */
const trackMapRef = ref<HTMLElement | null>(null)

/* 小车轨迹地图的实例 */
let mapInsTrack: any

let lushu: any

/* 轨迹路线 */
const lineData = [
  [112.55863627550298, 37.86535449354035],
  [112.56712335932487, 37.86535449354035],
  [112.5799752291123, 37.866315720275935],
  [112.58821982482502, 37.866507964105715],
  [112.59234212268136, 37.866315720275935],
  [112.59258461079057, 37.85997139015577],
  [112.59282709889975, 37.85381878648066],
  [112.59258461079057, 37.84901170452819],
  [112.59258461079057, 37.83881964551115],
  [112.59306958700896, 37.83478088959811],
  [112.59403953944575, 37.83151125720199],
  [112.59015972969863, 37.82227856519498],
  [112.57294307394565, 37.82381742809322],
  [112.5688207760893, 37.82362507200052],
  [112.55839378739381, 37.82381742809322],
  [112.54820928680755, 37.82343271540223],
  [112.54263206029601, 37.82381742809322]
]

/* 渲染轨迹回放地图 */
const renderTrackMap = () => {
  mapInsTrack = new BMapGL.Map(trackMapRef.value) // 创建Map实例
  mapInsTrack.centerAndZoom(new BMapGL.Point(112.55863627550298, 37.86535449354035), 12) // 初始化地图,设置中心点坐标和地图级别
  mapInsTrack.enableScrollWheelZoom(true) //开启鼠标滚轮缩放

  createLine()
  // 创建路书
  createLuShu()
}

/* 绘制线路 */
const createLine = () => {
  const polyline = new BMapGL.Polyline(
    lineData.map((item: any) => new BMapGL.Point(item[0], item[1])),
    {
      strokeColor: '#ff0000',
      strokeWeight: 4,
      strokeOpacity: 1
    }
  )
  mapInsTrack.addOverlay(polyline)
}

/* 创建路书 */
const createLuShu = () => {
  // 存在清除
  if (lushu) {
    lushu.stop()
    lushu = null
  }
  // 删除选择之前的坐标
  lushu = new BMapGLLib.LuShu(
    mapInsTrack,
    lineData.map((item: any) => new BMapGL.Point(item[0], item[1])),
    {
      autoView: true, // 是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
      icon: new BMapGL.Icon(
        'https://bj.bcebos.com/v1/mapopen/github/BMapGLLib/Lushu/examples/images/car.png',
        new BMapGL.Size(42, 52),
        { anchor: new BMapGL.Size(10, 10) }
      ),
      speed: 1000, // 速度
      enableRotation: true // 是否设置marker随着道路的走向进行旋转
    }
  )
}

const startTrackAnim = () => {
  lushu && lushu.start()
}

const pauseTrackAnim = () => {
  lushu && lushu.pause()
}

/* 渲染地图 */
onMounted(() => {
  renderTrackMap()
})

/* 销毁地图 */
onBeforeUnmount(() => {
  if (mapInsTrack) {
    mapInsTrack.destroy()
    mapInsTrack = null
  }
})
</script>

<template>
  <div ref="trackMapRef" style="height: 360px; max-width: 800px; margin-bottom: 16px"></div>
  <div>
    <el-button type="primary" @click="startTrackAnim"> 开始移动 </el-button>
    <el-button type="primary" @click="pauseTrackAnim"> 暂停移动 </el-button>
  </div>
</template>
