1. 下载依赖
npm i vue-amap --save
2. 初始化组件
在项目中全局初始化一次即可,你可以写在main.js中。
import VueAMap from 'vue-amap'
VueAMap.initAMapApiLoader({
key: '你的key',
// 插件集合
plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor'],
// 高德 sdk 版本,默认为 1.4.4
v: '1.4.4'
})
3. 加载地图
<el-amap
ref="amap"
:zoom="zoom" // Number类型 地图等级
:center="center" // Array类型 地图中心点
:style="{width: '100%', height: '100%', backgroundColor: 'rgba(0,0,0, 0.5)', borderRadius: '6px'}">
// 在这里写其它地图要素组件
<el-amap-marker/>
</el-amap>
更正一下:下面的所有events回调函数都不能直接写在dom元素身上,要写在data函数中,否则会报错
4. 加载点
<el-amap-marker
:offset="[-10,-26]" // 点的偏移量
:events="{ // 事件监听
init(m) {
// 事件监听
m.on('mouseover', () => dosomething )
m.on('mouseout', () => dosomething )
}
}"
:position="[lng, lat]" // 点的位置
animation="AMAP_ANIMATION_BOUNCE" // 点的动画
icon="图片路径" // 图标
/>
5. 添加点击事件
我查阅vue-amap的官方文档,上边写的,组件的点击事件直接使用click即可,相信很多人和我一样,都发现这么写,点击事件并不会起作用,vue-amap中组件的点击事件需要使用events来定义:
<el-amap-marker
:events="{ // 事件监听
init(m) {
// 事件监听
m.on('mouseover', () => dosomething )
m.on('mouseout', () => dosomething )
}
}"
/>
6. 加载文本
切记,文本组件不可以嵌套到el-amap-marker组件中,因为el-amap-marker并没有提供文本插槽,我们单独渲染并为其设置position即可。
<el-amap-text
:text="文本内容"
:events="{init(o) { o.setStyle({'color': 'red', 'font-size' : '12px'}) }}" // 设置文本样式,与css标准一致
textAlign="left" // 文本对齐方式
verticalAlign="top"
:position="[lng, lat]" // 文本坐标
/>
7. 加载线
<el-amap-polyline
:path="[[lng, lat], [lng, lat], ...]" // 设置线坐标集
stroke-color="#009aff"
:stroke-opacity="1"
:stroke-weight="6"
/>
8. 加载信息弹窗
<el-amap-info-window closeWhenClickMap :offset="[-6, -34]" :events="{init(m) {
m.on('open', () => isShow = true)
m.on('close', () => isShow = false)
}}" :position="[lng, lat]" :visible="isShow">
<div style="width: 300px;padding: 20px 0;">
我是个弹窗
</div>
</el-amap-info-window>
需要注意,官方文档写的open和close事件,我们并不可以直接使用,我们仍然需要借助events来实现。
9. 获取地图map实例
this.amap = this.$refs.amap.$$getInstance()
10. 地图定位最佳视野
this.amap.setFitView(null, false, [150, 60, 100, 60]) // 会根据地图上的所有要素来设置当前视野,简单方便
11. 使用拉框工具制作拉框查询
map.plugin(["AMap.MouseTool"], () => {
this.mousetool = new AMap.MouseTool(map)
this.mousetool.rectangle()
AMap.event.removeListener( this.mousetool, 'draw', this.listenDrawRect)
AMap.event.addListener( this.mousetool, 'draw', this.listenDrawRect)
})
// 禁用拉框功能,并清除矩形
this.mousetool.close(true)
12. 使用热力图层
// 加载热力图
this.amap.plugin(['AMap.Heatmap'], function() {
//初始化heatmap对象
this.heatmap = new AMap.Heatmap(that.amap, {
radius: 25, //给定半径
opacity: [0, 0.8],
})
let heatmapData = [{lng, lat, count}]
// 设置数据集
this.heatmap.setDataSet({
data: heatmapData,
max: 100
})
})
// 移除热力图
this.heatmap.setMap(null)
以上便是项目中常用的知识点。
—— 完结 ——