一、前言
在物流追踪、运动轨迹记录等场景中,地图轨迹可视化是常见需求。本文将以Vue3为例,详细介绍如何集成百度地图JavaScript API,并实现动态轨迹绘制功能。
二、准备工作
1. 注册百度地图开发者账号
访问百度地图开放平台注册账号
2. 创建应用获取AK
-
控制台 → 应用管理 → 我的应用 → 创建应用
-
应用类型选择「浏览器端」
-
记录获取的AK(如:
E4805d16520de693xxxxxxxx
)
三、项目搭建
1. 创建Vue项目
npm create vue@latest
2. 安装依赖
npm install vue-baidu-map-3x --save # 推荐使用封装好的Vue组件库
四、核心实现
1. 全局配置百度地图
main.ts
import { createApp } from 'vue' import BaiduMap from 'vue-baidu-map-3x' const app = createApp(App) app.use(BaiduMap, { ak: '您的AK', // 可选配置 v: '3.0', type: 'WebGL' }) app.mount('#app')
2. 基础地图组件
BaiduMap.vue
<template> <baidu-map class="map-container" :center="center" :zoom="zoom" @ready="mapReady" > <!-- 轨迹相关组件将在此处添加 --> </baidu-map> </template> <script setup lang="ts"> import { ref } from 'vue' const center = ref({ lng: 116.404, lat: 39.915 }) const zoom = ref(15) const mapReady = (e: any) => { console.log('地图初始化完成', e) } </script> <style scoped> .map-container { width: 100%; height: 600px; } </style>
五、轨迹绘制实现
1. 准备轨迹数据
// 示例轨迹数据(实际应从接口获取) const trackPoints = [ { lng: 116.301934, lat: 39.977552 }, { lng: 116.508328, lat: 39.919141 }, { lng: 116.527394, lat: 39.889146 } ]
2. 绘制轨迹折线
<template> <baidu-map ...> <bm-polyline :path="trackPoints" stroke-color="blue" :stroke-opacity="0.8" :stroke-weight="4" /> </baidu-map> </template>
3. 添加轨迹标记
<bm-marker v-for="(point, index) in trackPoints" :key="index" :position="point" :icon="{ url: require(`@/assets/marker${index === 0 ? '_start' : '_end'}.png`), size: { width: 32, height: 32 } }" > <bm-info-window :show="index === 0"> 轨迹点 {{ index + 1 }}<br> {{ point.lat.toFixed(4) }}, {{ point.lng.toFixed(4) }} </bm-info-window> </bm-marker>
六、高级功能扩展
1. 自动适应轨迹范围
const autoViewport = (points: any[]) => { const bounds = new BMap.Bounds() points.forEach(point => { bounds.extend(new BMap.Point(point.lng, point.lat)) }) map.value?.setViewport(bounds) }
2. 动态轨迹动画
// 使用BMAPLib实现轨迹动画 import { TrackAnimation } from 'vue-baidu-map-3x/lib/libs/TrackAnimation' let animation: TrackAnimation const startAnimation = () => { animation = new TrackAnimation(map.value, path, { duration: 10000, delay: 300 }) animation.start() } onUnmounted(() => { animation?.cancel() })
七、完整效果展示
功能清单:
-
基础地图展示
-
动态轨迹绘制
-
起止点标记
-
坐标信息窗口
-
自动视野调整
-
轨迹动画效果
八、常见问题解决
1. 地图不显示
-
检查AK是否有效
-
确认域名已加入白名单
-
检查容器宽高是否有效
2. 跨域问题
// vite.config.js export default defineConfig({ server: { proxy: { '/api': { target: 'https://api.map.baidu.com', changeOrigin: true } } } })
九、项目资源
十、总结
通过本文的步骤,我们可以快速在Vue3项目中集成百度地图并实现轨迹可视化功能。在实际项目中,建议:
-
将地图组件封装为独立模块
-
使用WebSocket实现实时轨迹更新
-
添加地图控件(缩放/比例尺)
-
结合ECharts实现热力图叠加