注:复制代码运行时请修改有效的key
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>百度地图验证鼠标是否点击在覆盖物内</title>
<style type="text/css" media="screen">
body,
html,
#map {
width: 100%;
height: 100%;
overflow: hidden;
margin: 0;
font-family: "微软雅黑";
}
.tips {
position: absolute;
top: 0;
left: 50%;
z-index: 9;
width: 400px;
padding: 20px;
font-weight: bold;
text-align: center;
background-color: #fff;
box-shadow: 0 2px 3px rgba(0,0,0,.2);
transform: translateX(-50%);
}
</style>
</head>
<body>
<div class="tips" id="tips">请用鼠标在地图上点击验证</div>
<div id="map"></div>
<!-- map -->
<script src="http://api.map.baidu.com/api?v=2.0&ak=你的key"></script>
<script src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
<script>
// 百度地图API功能
var map = new BMap.Map("map"); // 创建Map实例
var point = new BMap.Point(116.404, 39.915);
map.centerAndZoom(point, 15);
//创建矩形
var pStart = new BMap.Point(116.372214, 39.928985);
var pEnd = new BMap.Point(116.43478, 39.901901);
var rectangle = new BMap.Polygon([
new BMap.Point(pStart.lng, pStart.lat),
new BMap.Point(pEnd.lng, pStart.lat),
new BMap.Point(pEnd.lng, pEnd.lat),
new BMap.Point(pStart.lng, pEnd.lat)
], { strokeColor: "blue", strokeWeight: 4, strokeOpacity: 0.5 });
//增加矩形
map.addOverlay(rectangle);
//点击创建点
var tipsEle = document.getElementById('tips');
var tipsStr = '', tipsStyle = '';
map.addEventListener("click", function(e) {
var curPoint = new BMap.Point(e.point.lng, e.point.lat); //获取当前点击的坐标
var result = BMapLib.GeoUtils.isPointInPolygon(curPoint, rectangle); //计算坐标是否在矩形区域内
if (result) {
tipsStr = '点击的坐标在矩形区域内';
tipsStyle = 'color: green'
} else {
tipsStr = '点击的坐标不在矩形区域内';
tipsStyle = 'color: red'
}
tipsEle.innerText = tipsStr + '\n(lng: ' + e.point.lng + ', ' + 'lat: ' + e.point.lat + ')';
tipsEle.style.cssText = tipsStyle;
});
</script>
</body>
</html>