这是第一种办法,需要用到AreaRestriction_min.js这个js文件
map = new BMap.Map("allmap");
map.centerAndZoom(
new BMap.Point(114.34375, 30.49989),
15
);
map.setCurrentCity("成都");
map.enableScrollWheelZoom();
map.setMapStyleV2({
styleId: '83d85c903f83d83a839f8c507acd8792',
})
const bounds = map.getBounds(); //获取地图可视区域
const sw = bounds.getSouthWest(); //获取西南角的经纬度(左下角)
const ne = bounds.getNorthEast(); //获取东北角的经纬度(右上角)
const sws = new BMap.Point(sw.lng, sw.lat);
const nes = new BMap.Point(ne.lng, ne.lat);
const minZoom = 15;
const maxZoom = 18;
const boundary = new BMap.Bounds(
sws, nes,
);
BMapLib.AreaRestriction.setBounds(map, boundary);
map.setMinZoom(minZoom);
map.setMaxZoom(maxZoom);
map.setViewport(bounds);
//引入文件
<script type="text/javascript"
src="http://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js"></script>
<script type="text/javascript" src="http://api.map.baidu.com/library/BoundsTool/1.2/src/BoundsTool_min.js"></script>
第二种就是 百度地图官方文档有一个flyTo()的方法,和panTo()两个方法,panTo实测超出太长距离的时候,地图是不能返回的,暂时还没发现问题所在所以暂时用flyTo这个方法
const bounds = map.getBounds(); //获取地图可视区
const sws = new BMapGL.Point(bounds.sw.lng, bounds.sw.lat);
const nes = new BMapGL.Point(bounds.ne.lng, bounds.ne.lat);
const boundary = new BMapGL.Bounds(
sws, nes,
);
//boundary.containsBounds(map.getBounds())判断当前是否在可视区内
map.addEventListener("dragend", () => {
if (boundary.containsBounds(map.getBounds())) {
return;
} else {
map.flyTo(new BMapGL.Point(120.196689, 30.332336), 18);
}
});