在最近的項目中有需求需要拉框搜索區域內的一些特定信息
在百度上找到的參考有拉框放大和拉框搜索二個,但是都是封裝好的,它們並不會返回拉框區域的座標,所以我也無法使用,最後只能把拉框部分抽出來自己做個記錄
<!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>