百度地图验证鼠标是否点击在覆盖物内

注:复制代码运行时请修改有效的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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值