准备工作
- 在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的组件mapDrawCircle.vue,用于在地图上通过鼠标画出圆
- 通过v-if和组件传参,确定需要的地图组件
- 组件嵌套封装代码(一个地图上面有多个功能),相比一个地图上封装一个功能,这种方式加载速度更快
scottMap.vue
<template>
<div class="m-map">
<div id="js-container" class="map">正在加载数据 ...</div>
<div class="route">
<map-draw-circle v-if="isDrowCircle" :map="map" :AMap="AMap"></map-draw-circle>
</div>
</div>
</template>
<script>
import MapDrawCircle from './scottMap/mapDrawCircle.vue'
export default {
name: 'mapIndex',
components: { MapDrawCircle },
props: {
isDrowCircle: {
type: Boolean,
default: false
}
},
data () {
return {
AMap: null,
map: null,
layer: '',
mapConfig: {
zoom: 10,
center: [117.27, 31.86],
layers: []
}
}
},
mounted () {
this.initMap()
},
methods: {
initMap () {
this.AMap = window.AMap
this.map = new AMap.Map('js-container', this.mapConfig)
}
}
}
</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>
mapDrawCircle.vue
<template>
<div>
<el-button @click="doDrowCircle">是否画圆</el-button>
<el-button @click="CancleDrowCircle">清空画圆</el-button>
</div>
</template>
<script>
export default {
name: 'mapDrawCirle',
props: ['map', 'AMap'],
components: {},
data () {
return {
mouseTool: null,
LngLatList: [
{
lng: 114.081505,
lat: 22.576792,
address: '1111',
tel: 1111
},
{
lng: 114.080175,
lat: 22.576178,
address: '22222',
tel: 22222
},
{
lng: 114.082874,
lat: 22.579962,
address: '3333',
tel: 3333
},
{
lng: 114.078604,
lat: 22.579903,
address: '4444',
tel: 44444
}
]
}
},
methods: {
doDrowCircle () {
const that = this
that.map.plugin(['AMap.MouseTool'], function () {
that.mousetool = new AMap.MouseTool(that.map)
that.mousetool.circle()
that.mousetool.on('draw', function (e) {
const circle = e.obj
that.LngLatList.forEach(item => {
const myLngLat = [item.lng, item.lat]
if (circle.contains(myLngLat)) {
console.log(item)
}
})
})
})
},
CancleDrowCircle () {
this.mousetool.close(true)
}
}
}
</script>
<style lang='less' scoped>
</style>