vue 实现地图路线
Vue 实现地图路线的方法
使用 Vue 实现地图路线通常需要结合第三方地图 API(如高德、百度或 Google Maps)。以下是基于高德地图的实现方法。
安装高德地图 SDK
在项目中引入高德地图 JavaScript API,可以通过 CDN 或 npm 安装。以下是 npm 安装方式:

npm install @amap/amap-jsapi-loader --save
初始化地图组件
创建一个 Vue 组件用于加载地图。在组件中引入高德地图 SDK 并初始化地图实例。

<template>
<div id="map-container" style="width: 100%; height: 500px;"></div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
name: 'MapRoute',
data() {
return {
map: null,
path: [
[116.478935, 39.997761],
[116.478939, 39.997825],
[116.478912, 39.998549],
[116.478912, 39.998549],
[116.478998, 39.998555],
[116.478998, 39.998555],
[116.479282, 39.99856],
[116.479658, 39.998528],
[116.480151, 39.998453],
[116.480784, 39.998302],
],
};
},
mounted() {
this.initMap();
},
methods: {
initMap() {
AMapLoader.load({
key: '你的高德地图Key',
version: '2.0',
plugins: ['AMap.Driving'],
})
.then((AMap) => {
this.map = new AMap.Map('map-container', {
viewMode: '2D',
zoom: 13,
center: [116.397428, 39.90923],
});
this.drawRoute(AMap);
})
.catch((e) => {
console.error(e);
});
},
drawRoute(AMap) {
const driving = new AMap.Driving({
map: this.map,
panel: 'panel',
});
driving.search(
new AMap.LngLat(116.379028, 39.865042),
new AMap.LngLat(116.427281, 39.903719),
(status, result) => {
if (status === 'complete') {
console.log('绘制路线完成');
} else {
console.error('路线规划失败:', result);
}
}
);
},
},
};
</script>
自定义路线样式
如果需要自定义路线样式,可以通过 polyline 实现。以下是绘制自定义路径的代码示例:
drawCustomRoute(AMap) {
const polyline = new AMap.Polyline({
path: this.path,
isOutline: true,
outlineColor: '#ffeeff',
borderWeight: 1,
strokeColor: '#3366FF',
strokeOpacity: 1,
strokeWeight: 6,
strokeStyle: 'solid',
lineJoin: 'round',
lineCap: 'round',
zIndex: 50,
});
this.map.add(polyline);
this.map.setFitView();
}
添加路线标记点
可以在地图上添加起点和终点的标记点,增强用户体验。
addMarkers(AMap) {
const startMarker = new AMap.Marker({
position: this.path[0],
icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
map: this.map,
});
const endMarker = new AMap.Marker({
position: this.path[this.path.length - 1],
icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
map: this.map,
});
}
注意事项
- 高德地图的 Key 需要注册并获取,替换代码中的
你的高德地图Key。 - 路径数据
path可以根据实际需求动态获取或计算。 - 如果需要更复杂的路线规划(如避堵、高速优先等),可以使用
AMap.Driving的更多参数配置。






