1.注册账号并申请Key
1. 首先,注册开发者账号,成为高德开放平台开发者
2. 登录之后,在进入「应用管理」 页面「创建新应用」
3. 为应用添加 Key,「服务平台」一项请选择「 Web 端 ( JSAPI ) 」,设置域名白名单,可选(建议设置域名白名单)。
4. 添加成功后,可获取到key值和安全密钥jscode,在根页面下引用 public/index.html
HTML
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode:'您申请的安全密钥',
}
</script>
5. 在完成如上准备工作之后,您便可以开始参考后续文档进行开发了。点击查看更多
2.地图组件开发和使用
1.按 NPM 方式安装使用 Loader :
npm i @amap/amap-jsapi-loader --save
2.在项目中新建 MapContainer.vue 文件,用作地图组件。
3.在 MapContainer.vue 地图组件中创建 div 标签作为地图容器 ,并设置地图容器的 id 属性为 container;
HTML
<template>
<div id="container"></div>
</template>
4.设置地图容器样式
CSS
<style scoped>
#container{
padding:0px;
margin: 0px;
width: 100%;
height: 800px;
}
</style>
5.在地图组件 MapContainer.vue 中引入 amap-jsapi-loader
JavaScript
import AMapLoader from '@amap/amap-jsapi-loader';
在 Vue2 中使用方式:
在 data 函数中不声明 map 对象,可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
JavaScript
data(){
return{
//此处不声明 map 对象,可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
//map:null,
}
},
6.地图初始化函数 initMap
JavaScript
methods:{
initMap(){
AMapLoader.load({
key:"", // 申请好的Web端开发者Key,首次调用 load 时必填
version:"2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins:[''], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
}).then((AMap)=>{
this.map = new AMap.Map("container",{ //设置地图容器id
viewMode:"3D", //是否为3D地图模式
zoom:5, //初始化地图级别
center:[105.602725,37.076636], //初始化地图中心点位置
});
}).catch(e=>{
console.log(e);
})
},
},
提示:JSAPI Loader是我们提供的 API 加载器,其加载方式为异步加载 JS API 内容,所以在使用 AMap 对象前需进行验证,这种使用场景下,
JSAPI不会阻塞页面其他内容的执行和解析,但是 JSAPI 的脚本解析将有可能发生其他脚本资源执行之后,因为需要特别处理,以保证在 AMap对象完整生成之后再调用 JSAPI 的相关接口,否则有可能报错。
7.调用地图初始化函数:mounted 函数会在 DOM 初始化完成后调用,建议在 mounted 函数中调用地图初始化方法。
JavaScript
mounted(){
//DOM初始化完成进行地图初始化
this.initMap();
}
3.案列
1.效果图
2.组件代码
<template>
<div>
<div id="container"></div>
</div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
data () {
return {
map: null,
imgUrl: require('../../assets/logo.png')
}
},
mounted () {
this.initMap()
},
methods: {
initMap () {
const that = this
AMapLoader.load({
key: 'df951794e92acfdb0efc2346c652f852', // 申请好的Web端开发者Key,首次调用 load 时必填
version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: [
'AMap.ToolBar',
'AMap.Scale',
'AMap.DistrictSearch',
'AMap.HawkEye',
'AMap.Polyline',
'AMap.MapType',
'AMap.Polygon',
'AMap.DistrictLayer',
'AMap.Geolocation'
] // 需要使用的的插件列表,如比例尺'AMap.Scale'等
}).then((AMap) => {
const opts = {
subdistrict: 1,
extensions: 'all',
level: 'city'
}
// 利用行政区查询获取边界构建mask路径
// 也可以直接通过经纬度构建mask路径
const district = new AMap.DistrictSearch(opts)
district.search('合肥市', function (status, result) {
const bounds = result.districtList[0].boundaries
const mask = []
for (let i = 0; i < bounds.length; i += 1) {
mask.push([bounds[i]])
}
that.map = new AMap.Map('container', { // 设置地图容器id
mask: mask, // 边界路径
viewMode: '3D', // 是否为3D地图模式
zoom: 9, // 初始化地图级别
resizeEnable: true,
center: [117.27, 31.86], // 初始化地图中心点位置
// 官方提供的样式https://lbs.amap.com/api/javascript-api/guide/map/map-style
mapStyle: 'amap://styles/darkblue' // 设置地图的显示样式
})
// 添加描边(区域掩膜)
for (let i = 0; i < bounds.length; i += 1) {
new AMap.Polyline({
path: bounds[i],
strokeColor: 'red', // 边界的颜色
strokeWeight: 2, // 边界的边框的粗细
map: that.map
})
}
// 在图面添加工具条控件,工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
that.map.addControl(new AMap.ToolBar())
// 在图面添加比例尺控件,展示地图在当前层级和纬度下的比例尺
that.map.addControl(new AMap.Scale())
// 在图面添加鹰眼控件,在地图右下角显示地图的缩略图
that.map.addControl(new AMap.HawkEye())
// 在图面添加类别切换控件,实现默认图层与卫星图、实施交通图层之间切换的控制
that.map.addControl(new AMap.MapType())
// 在图面添加定位控件,用来获取和展示用户主机所在的经纬度位置(自身定位)
// this.map.addControl(new AMap.Geolocation())
// 创建一个点标记图标
const commonIcon = new AMap.Icon({
size: new AMap.Size(25, 34), // 图标尺寸
image: that.imgUrl, // 图标地址
imageSize: new AMap.Size(25, 34), // 图标所用图片的大小
imageOffset: new AMap.Pixel(-0, -0) // 图片取图偏移量
})
// 将 icon 传入 marker(如果知道经纬度的数组可以遍历添加)
const startMarker1 = new AMap.Marker({
position: new AMap.LngLat(117.28, 31.86),
icon: commonIcon,
map: that.map,
offset: new AMap.Pixel(-13, -30)
})
const startMarker2 = new AMap.Marker({
position: new AMap.LngLat(117.25, 31.87),
icon: commonIcon,
map: that.map,
offset: new AMap.Pixel(-13, -30)
})
const startMarker3 = new AMap.Marker({
position: new AMap.LngLat(117.21, 31.88),
icon: commonIcon,
map: that.map,
offset: new AMap.Pixel(-13, -30)
})
// 模拟后端返回处理好的数据
const arrPosition = [startMarker1, startMarker2, startMarker3]
// 给每个标记点添加点击事件,数据集里面不加map:this.map则需要添加下面这行代码
// this.map.add(arrPosition)
const infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) })
for (let i = 0; i < arrPosition.length; i++) {
const marker = (arrPosition[i])
marker.content = `<div style="color:black; zIndex: 99999; margin-top: 5px"> ${i} + 222222 `
marker.on('click', markerClick)
marker.emit('click', { target: marker })
}
function markerClick (e) {
infoWindow.setContent(e.target.content)
infoWindow.open(that.map, e.target.getPosition())
}
// 如果只是需要行政区划分区分颜色块则可以使用下面代码,但是区域的事件我没找到在哪块添加 以下
AMap.plugin(['AMap.DistrictLayer'], function () {
const disProvince = new AMap.DistrictLayer.Province({
city: '合肥市',
zIndex: 12,
depth: 2,
adcode: ['340122', '340102', '340111', '340103', '340104', '340121', '340123', '340124', '340181'], // 重点:添加要划分的子行政区码
styles: {
fill: function (properties) {
const adcode = properties.adcode
return getColorByAdcode(adcode)
},
fillOpacity: 0.5,
'province-stroke': '#09b8bf',
'city-stroke': '#09b8bf',
'county-stroke': '#09b8bf' // 线条颜色
}
})
disProvince.setMap(that.map)
// disProvince.on('mouseover', function (event, feature) {
// disProvince.setStyles({
// fillOpacity: 0.7,
// fill: '#7bccc4'
// })
// console.log(event, '1111', feature)
// })
// disProvince.on('mouseout', (event) => {
// disProvince.setStyles({
// fillOpacity: 0.5,
// fill: '#ccebc5'
// })
// console.log(event.target)
// })
})
// 随机颜色
const getColorByAdcode = (adcode) => {
const colors = {}
if (!colors[adcode]) colors[adcode] = '#' + parseInt(0x1000000 * Math.random()).toString(16).padStart(6, '0')
return colors[adcode]
}
// 如果只是需要行政区划分区分颜色块则可以使用下面代码,但是区域的事件我没找到在哪块添加 以上
})
}).catch(e => {
console.log(e)
})
}
}
}
</script>
<style lang="scss" scoped>
#container {
padding: 0px;
margin: 0px;
width: 900px;
height: 600px;
background: rgba(255, 255, 255, 0) !important; // 地图背景透明
}
</style>
每块片区的事件没有添加,还在研究中,有大佬的话还望指点指点