注册申请百度秘钥
1、具体注册教程引入就不在这展示了,具体可以查看API
2、[链接地址](https://lbsyun.baidu.com/index.php)
引入百度key
1、在index.html文件中引入百度地图JavaScript API接口
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=申请的秘钥"></script>
定义显示地图容器
<div id="allmap" ref="allmap" />
初始化百度地图
//全局定义变量_status 用为判断当前为省级还是楼宇显示(1、省份2、楼宇)
initMap() {
var _this = this
var map = new window.BMap.Map('allmap', {
enableMapClick: false,//禁止点击其他区域内容
minZoom : 最小缩放级别,
maxZoom : 最大缩放级别
}) // 创建地图实例
_this.map = map
var point = new window.BMap.Point(116.29881, 40.039913) // 创建点坐标
map.centerAndZoom(point, 9) // 初始化地图,设置中心点坐标和地图级别
map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
//百度地图获取滚轮缩放级别API方法
map.addEventListener('zoomend', function(e) {
var ZoomNum = map.getZoom() // 获取百度地图的缩放级别
if (ZoomNum <= _this.zoomLimit && _this._status == 2) {
_this._status = 1 // 判断当前的缩放级别大于等于默认的级别如果等于则显示时楼宇数据
} else if (ZoomNum > _this.zoomLimit && _this._status == 1) {
_this._status = 2 // 判断当前的缩放级别小于默认的级别如果等于则显示时楼宇数据
}
_this.showMapData() //封装showmapData方法函数用于显示楼宇还是省份的数据
})
},
```
通过zoom的大小判断展示不同的级别数据
showMapData(type) {
var _this = this
if (!_this.map) return
_this.map.clearOverlays()//清楚覆盖物
if (_this._status == 1) { // 显示城市数据
_this.showProvince()
} else if (_this._status == 2) { // 显示楼宇数据
_this.showBuilds()
}
},
城市数据
showProvince(){
var _this = this
this.geoCoordMap.forEach((e, i) => { //自己可以自定义城市的展示数据
const pointNumber = new window.BMap.Point(e.longi, e.lati)
const regionName = e.regionName
const buildCount = e.buildCount
var label = new window.BMap.Label('<p style="margin:0">'+regionName+':'+'  '+buildCount+'</p>', {
offset: new window.BMap.Size(25, 5)
})
label.setStyle({ color: 'rgba(255,255,255,1)',
fontSize: '14px', padding: '0px 12px 5px 12px', height: '34px',
lineHeight: '34px', fontFamily: '微软雅黑',
background: 'rgba(37,98,255,1)', border: '0',
width: '100px', textAlign: 'center', borderRadius: '2px 0px 2px 2px'
})
const markers = new window.BMap.Marker(pointNumber, { icon: _this.defaultIcon })
_this.map.addOverlay(markers)
markers.setLabel(label)
markers.addEventListener('mouseover', function(event) {
var tip = markers.Bc
tip.classList.add('marker')
this.setIcon(_this.hoverIcon)
})
markers.addEventListener('mouseout', function(event) {
var tip = markers.Bc
this.setIcon(_this.defaultIcon)
tip.classList.remove('marker')
})
})
}
楼宇数据
showBuilds(){
var _this = this
var data = _this.res //楼宇展示数据
data.forEach((e, i) => {
const point = new window.BMap.Point(e.longi, e.lati)//楼宇的经度纬度
_this.createMarkers(e.buildId, e.buildName, point, e)
})
}
createMarkers(build, name, point, item) {
var _this = this
const markers = new window.BMap.Marker(point, { icon: _this.defaultIcon })
_this.map.addOverlay(markers)//打点坐标点Marker
markers.setLabel(label)//加载坐标点
markers.addEventListener('mouseover', function(event) {
//鼠标滑过
})
markers.addEventListener('mouseout', function(event) {
//鼠标离开
})
markers.addEventListener('click', function(event) {
//鼠标点击
})
},