Skip to content

TrackMarker

安装

bash
npm i @likcheung/track-marker

案例

以 vue 为例

vue
<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import TrackMaker from '@likcheung/track-marker'
import player from './player.vue'
import api from './api'

window._AMapSecurityConfig = {
  securityJsCode: <your AMap private secret>
}

defineOptions({ name: 'TrackMarker' })

// 控制栏显示
const toolsShow = ref(false)

// 进度条
const progress = ref(0)
const speed = ref(1500)

// 初始化 trackMarker
const trackMarker = new TrackMaker({
  duration: speed.value
})
// 监听进度事件
trackMarker.onProgressChange((p: number) => {
  progress.value = +p.toFixed(1) * 100
})
// 监听结束事件
trackMarker.onEnd(() => {
  // 动画结束后,marker 会自动返回起点
  nextTick(() => (progress.value = 0))
})
// 进度条拖动
const progressTraling = (progress: number) => {
  trackMarker.setProgress(progress / 100)
}
// 速度改变
const speedChange = (speed: number) => {
  trackMarker.setConfig({ duration: speed })
}

const init = async () => {
  const AMap = await AMapLoader.load({
    key: <your AMap key>,
    version: '2.0'
  })

  // 通过api获取路径数据
  const lineArr = await api()

  // 地图设置
  AMap.plugin('AMap.MoveAnimation', function () {
    const map = new AMap.Map('container', {
      resizeEnable: true,
      center: lineArr[0],
      zoom: 17
    })
    const marker = new AMap.Marker({
      map: map,
      position: lineArr[0],
      icon: 'https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png',
      offset: new AMap.Pixel(-13, -26)
    })

    new AMap.Polyline({
      map: map,
      path: lineArr,
      showDir: true,
      strokeColor: '#28F', //线颜色
      // strokeOpacity: 1,     //线透明度
      strokeWeight: 6 //线宽
      // strokeStyle: "solid"  //线样式
    })
    map.setFitView()

    // 为 trackMarker 设置 marker 实例
    trackMarker.set(marker, lineArr)
    // 地图初始化完成后,显示控制栏
    toolsShow.value = true
  })
}

onMounted(init)
</script>

<template>
  <div class="comp">
    <div class="tools" v-show="toolsShow">
      <player
        v-model:progress="progress"
        v-model:speed="speed"
        @play="() => trackMarker.start()"
        @pause="() => trackMarker.pause()"
        @trail="progressTraling"
        @update:speed="speedChange"
      />
    </div>
    <div id="container"></div>
  </div>
</template>