准备工作
- 在public中的index.html中初始化地图
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
- 在 .eslintrc.js 中配置AMap和AMapUI
globals: {
"AMap": "true",
"AMapUI":"true",
}
实现思路
- 封装一个全局组件scottMap.vue,用于加载地图
- 封装一个基于scottMap.vue的组件mapDriveLine.vue,用于在地图上画出驾车路线
- 通过v-if和组件传参,确定需要的地图组件
- 组件嵌套封装代码(一个地图上面有多个功能),相比一个地图上封装一个功能,这种方式加载速度更快
scottMap.vue
<template>
<div class="m-map">
<div id="js-container" class="map">正在加载数据 ...</div>
<div class="route">
<map-drive-line v-if="isDriveLine" :map="map" :AMap="AMap"></map-drive-line>
</div>
</div>
</template>
<script>
import MapDriveLine from './scottMap/mapDriveLine.vue'
export default {
name: 'mapIndex',
components: { MapDriveLine },
props: {
isDriveLine: {
type: Boolean,
default: false
}
},
data () {
return {
AMap: null,
map: null
}
},
mounted () {
this.initMap()
},
methods: {
initMap () {
this.AMap = window.AMap
this.map = new AMap.Map('js-container', {
zoom: 10,
center: [117.27, 31.86]
})
}
}
}
</script>
<style lang="css">
.m-map{ min-width: 500px; min-height: 300px; position: relative; }
.m-map .map{ width: 100%; height: 100%; }
.route{
position: absolute;
top: 10px;
left: 200px;
display: flex;
}
</style>
mapDriveLine.vue
<template>
<div>
<el-button @click="drawRoute2">绘制路线2</el-button>
<el-button @click="closeRoute2">关闭路线2</el-button>
</div>
</template>
<script>
export default {
name: 'MapDriveLine',
props: ['map', 'AMap'],
components: {},
data () {
return {
driving: null
}
},
methods: {
drawRoute2 () {
const that = this
that.AMap.plugin('AMap.Driving', function () {
if (!that.driving) {
that.driving = new AMap.Driving({
map: that.map,
showTraffic: false,
policy: that.AMap.DrivingPolicy.LEAST_TIME
})
var startLngLat = [114.078454, 22.579593]
var endLngLat = [114.082166, 22.57676]
that.driving.search(startLngLat, endLngLat, function (status, result) {})
}
})
},
closeRoute2 () {
if (this.driving) {
this.driving.clear()
this.driving = null
}
}
}
}
</script>
<style lang='less' scoped>
</style>
页面调用
<scottMap class="scottMap" :isDriveLine="true"></scottMap>