高德地图-----图层切换
准备工作在public中的index.html中初始化地图<script src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>在 .eslintrc.js 中配置AMap和AMapUIglobals: {"AMap": "true","AMapUI":"true",}实现思路封装一个全局
·
准备工作
- 在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的组件mapLayer.vue,用于在地图上切换图层
- 子组件向父组件传递用户选择的图层,父组件渲染
- 通过v-if和组件传参,确定需要的地图组件
- 组件嵌套封装代码(一个地图上面有多个功能),相比一个地图上封装一个功能,这种方式加载速度更快
父组件scottMap.vue
<template>
<div class="m-map">
<div id="js-container" class="map">正在加载数据 ...</div>
<div class="route">
<map-layer v-if="isLayer" @layerName="changeLayer"></map-layer>
</div>
</div>
</template>
<script>
import MapLayer from './scottMap/mapLayer.vue'
/*
传递参数:
1. isLayer: 是否需要切换图层
*/
export default {
name: 'mapIndex',
components: { MapLayer },
props: {
isLayer: {
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)
},
// 切换图层
changeLayer (val) {
switch (val) {
case 'layer':
this.layer = new AMap.TileLayer()
break
case 'satellite':
this.layer = new AMap.TileLayer.Satellite()
break
case 'roadNet':
this.layer = new AMap.TileLayer.RoadNet()
break
case 'traffic':
this.layer = new AMap.TileLayer.Traffic()
break
default:
this.$notify({
title: '提示',
message: '切换图层失败!',
duration: 3000
})
break
}
this.mapConfig.layers.splice(0, 1, this.layer)
this.map.destroy()
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>
子组件 mapLayer.vue
<template>
<div>
<el-dropdown trigger="click" @command="handleCommand">
<el-button>
切换图层<i class="el-icon-arrow-down el-icon--right"></i>
</el-button>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="layer">标准图层</el-dropdown-item>
<el-dropdown-item command="satellite">卫星图层</el-dropdown-item>
<el-dropdown-item command="roadNet">路网图层</el-dropdown-item>
<el-dropdown-item command="traffic">实时交通图层</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</template>
<script>
export default {
name: '',
components: {},
data () {
return {}
},
methods: {
handleCommand (command) {
this.$emit('layerName', command)
}
}
}
</script>
<style lang='less' scoped>
</style>
页面调用
<scottMap :isLayer="true" > </scottMap>
更多推荐
已为社区贡献7条内容
所有评论(0)