这次介绍在vue里面使用基础的地图组件,用的是高德地图

- 先要在高德地图开发平台上注册一个应用,选JavaScript API,就能得到一个app key,请求它的地图都要用到这个key。

- 然后创建一个地图vue组件,在里面定义公共配置。
// 高度和宽度由外面传入
<template>
<div :id="id"
:style="{width:width+'px',height:height+'px'}"
class="map-index">
</div>
</template>
然后引入高德的地图不能直接写入一个script标签,需要用到异步加载,看看官方的用法:

url后面需要拼接上一个初始化地图的回调函数,名字可以自定义,在这里配置地图。
在vue就在mounted中编写,补上上面的prop变量:
props: {
height: {
type: Number,
default: 300
},
width: {
type: Number,
default: 300
},
point: { // 地图中心点的经纬度
type: Array,
default() {
return [116.46, 39.92]
}
}
},
data() {
return {
id: `map`, // 地图dom的id,下面会动态配置
key: 'xxxx' // 高德app的key
}
},
因为是作为一个公共的组件,所以id就动态随机生出,防止重复,然后要把这个地图实例保存起来,后面还有一些操作用到。
mounted() {
let _this = this
_this.id = `map${Math.random().toString().slice(4, 6)}`
window.onmaploaded = () => { // 回调函数
// 声明地图类
let map = new window.AMap.Map(_this.id, {
resizeEnable: true, // 允许缩放
zomm: 11, // 缩放层级
center: this.point // 中心点坐标
})
_this.map = map // 保存这个地图实例
// 插件
window.AMap.plugin('AMap.ToolBar', () => { // 缩放条
let toolbar = new window.AMap.ToolBar()
map.addControl(toolbar)
})
// marker为地图上的标记物
let marker = new window.AMap.Marker({
icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png', // 官方提供的icon
position: _this.point // 标记点的坐标,和地图中心坐标一致
})
_this.marker = marker // 保存这个标记点类
marker.setMap(map) //为Marker指定目标显示地图
}
// 声明script标签
const url = `https://webapi.amap.com/maps?v=1.4.15&key=${_this.key}&callback=onmaploaded`
var jsapi = document.createElement('script');
jsapi.charset = 'utf-8';
jsapi.src = url;
document.head.appendChild(jsapi);
}
这样就完成了基础的地图声明,如果想再简化,可以把缩放条和标记点去掉,按我上面贴的官方图敲就是一个最基础的地图实例。
因为是做成一个公共组件,当传入的经纬度有变化的时候,就应该手动刷新地图和标记点。
监听一下prop的point变化:
watch: {
point(val, old) {
this.map.setCenter(val) // 设置地图显示的中心点
this.marker.setPosition(val) // 设置点标记位置
}
}
这就是上面为什么保存map和marker的原因,方便在监听中使用,都是官方的api,有再复杂的需求看官方的api再增加就可以。
网友评论