百度地图缩放功能,结合自定义缩放控件
程序员文章站
2022-07-03 18:05:47
...
实现地图缩放功能:
- 滚动鼠标的滚轮
- 点击自定义缩放控件,点击 + 是放大地图,点击 - 是缩小地图
- 地图的缩放级别在4-19之间,超出这个范围将会有提示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>地图缩放</title>
<style>
body,
html {
padding: 10px;
height: 90%;
}
#map {
width: 95%;
height: 90%;
overflow: hidden;
margin: 0;
font-family: '微软雅黑';
position: relative;
}
#allmap {
width: 100%;
height: 100%;
}
#zoomBtn {
position: absolute;
right: 0px;
bottom: 0px;
z-index: 4;
padding: 5px;
width: 28px;
background-color: #333740;
color: #ccc;
text-align: center;
font-size: 14px;
border-radius: 5px;
padding-bottom: 5px;
}
#zoomBtn>div:nth-child(-n + 2) {
border-bottom: 1px solid #ccc;
}
#zoomBtn>div:nth-child(odd) {
cursor: pointer;
user-select: none;
}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=gHoGaCVBIxUMSMKvSYr0XfiZQO1wnPdi"></script>
</head>
<body>
<div id="map">
<p>
鼠标滚动实现地图的缩放
<br>
当前地图级别为:<span class="show" style='color:red;font-size:20px;font-weight: 700'>11</span>
</p>
<div id="allmap"></div>
<div id="zoomBtn">
<div onclick="addZoom()">+</div>
<div class="wrap_show">11</div>
<div onclick="delZoom()">-</div>
</div>
</div>
</body>
<script type="text/javascript">
let map = new BMap.Map('allmap') //创建map实例
map.centerAndZoom(new BMap.Point(116.404, 39.915), 11) // 初始化地图,设置中心点坐标和地图级别
map.enableScrollWheelZoom(true) //开启鼠标滚轮缩放
mapWheel()
let mapZoom = 11//地图的缩放级别
//鼠标滚动致使地图上的放大缩小---缩放区间在4-19之间
function mapWheel(params) {
document.querySelector('#allmap').onmousewheel = e => {
//放大 getZoom返回地图当前缩放级别
if (e.wheelDelta > 0) {
mapZoom = map.getZoom() + 1
if (mapZoom > 19) {
mapZoom = 19
alert('地图级别在4-19之间')
}
}
//缩小
if (e.wheelDelta < 0) {
mapZoom = map.getZoom() - 1
if (mapZoom < 4) {
mapZoom = 4
alert('地图级别在4-19之间')
}
}
document.querySelector('.wrap_show').innerHTML = mapZoom
document.querySelector('.show').innerHTML = mapZoom
}
}
//加大地图级别
function addZoom(params) {
map.zoomIn() //放大一级视图
if (mapZoom < 19) {
mapZoom++;
} else {
alert('地图级别在4-19之间')
}
document.querySelector('.wrap_show').innerHTML = mapZoom
document.querySelector('.show').innerHTML = mapZoom
}
//缩小地图级别
function delZoom(params) {
map.zoomOut() //缩小一级视图
if (mapZoom > 4) {
mapZoom--;
} else {
alert('地图级别在4-19之间')
}
document.querySelector('.wrap_show').innerHTML = mapZoom
document.querySelector('.show').innerHTML = mapZoom
}
</script>