vue实现地图导航
使用高德地图API实现Vue地图导航
安装高德地图JavaScript API的Vue封装库
npm install @amap/amap-jsapi-loader --save
在Vue组件中引入并初始化地图

import AMapLoader from '@amap/amap-jsapi-loader'
export default {
data() {
return {
map: null,
AMap: null
}
},
mounted() {
this.initMap()
},
methods: {
initMap() {
AMapLoader.load({
key: '您的高德地图Key', // 替换为实际key
version: '2.0',
plugins: ['AMap.Driving']
}).then((AMap) => {
this.AMap = AMap
this.map = new AMap.Map('map-container', {
viewMode: '2D',
zoom: 13,
center: [116.397428, 39.90923] // 默认北京中心点
})
})
}
}
}
添加路线规划功能
在组件中添加导航方法
methods: {
drawRoute(start, end) {
const driving = new this.AMap.Driving({
map: this.map,
policy: this.AMap.DrivingPolicy.LEAST_TIME
})
driving.search([
{ keyword: start, city: '城市名' },
{ keyword: end, city: '城市名' }
], (status, result) => {
if (status === 'complete') {
console.log('路线规划完成')
} else {
console.error('路线规划失败', result)
}
})
}
}
添加地图标记和信息窗口
实现地点标记和信息展示

addMarker(position, title) {
const marker = new this.AMap.Marker({
position: position,
title: title,
map: this.map
})
const infoWindow = new this.AMap.InfoWindow({
content: `<div>${title}</div>`
})
marker.on('click', () => {
infoWindow.open(this.map, marker.getPosition())
})
}
集成位置搜索功能
添加地点搜索方法
searchPlace(keyword) {
const placeSearch = new this.AMap.PlaceSearch({
map: this.map,
city: '城市名'
})
placeSearch.search(keyword, (status, result) => {
if (status === 'complete') {
result.poiList.pois.forEach(poi => {
this.addMarker([poi.location.lng, poi.location.lat], poi.name)
})
}
})
}
响应式地图容器样式
确保地图容器正确显示
<template>
<div id="map-container" style="width: 100%; height: 500px;"></div>
</template>
注意事项
- 需要在项目中引入高德地图的安全密钥
- 使用前需在高德开放平台申请Web端Key
- 实际部署时需要考虑跨域问题和https协议要求
- 移动端需额外处理触摸事件和响应式布局






