在最近的项目中有需求需要拉框搜索区域内的一些特定信息
在百度上找到的参考有拉框放大和拉框搜索二个,但是都是封装好的,它们并不会返回拉框区域的坐标,所以我也无法使用,最后只能把拉框部分抽出来自己做个记录
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拉框</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.4"></script>
<script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0"></script>
</script>
</head>
<style>
#container {
width: 100%;
height: calc(100vh - 50px);
margin-top: 10px;
}
</style>
<body>
<button onclick="openBut()">开启</button>
<button onclick="closeBut()">关闭</button>
<div id="container"></div>
</body>
</html>
<script type="text/javascript">
let map = new BMap.Map("container")
let point = new BMap.Point(117.263865, 34.151257)
map.centerAndZoom(point, 15)
map.enableScrollWheelZoom()
let a1 = ""
let b1 = ""
let a2 = ""
let b2 = ""
let polygon = null
// 鼠标拖动事件监听
let huafang = function (e) {
if (polygon) {
map.removeOverlay(polygon)
polygon = null
}
a2 = e.point.lng
b2 = e.point.lat
polygon = new BMap.Polygon([
new BMap.Point(a1, b1),
new BMap.Point(a2, b1),
new BMap.Point(a2, b2),
new BMap.Point(a1, b2)
], {
strokeColor: "blue",
strokeWeight: 6,
strokeOpacity: 0.5
});
map.addOverlay(polygon)
}
// 开启拉框
function openBut() {
map.setDefaultCursor('crosshair')
map.disableDragging()
}
// 关闭拉框
function closeBut() {
map.setDefaultCursor("url('bird.cur')")
map.enableDragging()
}
// 鼠标按下
map.addEventListener("mousedown", function (e) {
a1 = e.point.lng
b1 = e.point.lat
beginMove()
})
// 鼠标释放
map.addEventListener("mouseup", function (e) {
a1 = ''
a2 = ''
b1 = ''
b2 = ''
map.removeEventListener('mousemove', huafang)
map.removeOverlay(polygon)
polygon = null
})
// 启用拖动事件监听
function beginMove() {
map.addEventListener("mousemove", huafang)
}
</script>