百度地圖電子圍欄判斷

風靈使發表於2018-09-05

Index.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=2.0&ak=O**************k"></script>
<script type="text/javascript" src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
<!--載入滑鼠繪製工具-->
<script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
<link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css"/>
<style type="text/css">
        table{
            font-size:14px;
        }
</style>
</head>
<body>
<div style="float:left;width:100%;height:500px;border:1px solid gray" id="container">
</div>
<div style="float:left;width:100%;border:1px solid gray" id="control">
    <table style="width:100%;">
    <tr>
        <td colspan="2">
            判斷點是否在指定區域內:
        </td>
    </tr>
    <tr>
        <td>
            <button onclick="ptInPolygon()">判斷</button>
            <button onclick="clearPolygon()">清除</button>
        </td>
    </tr>
    </table>
</div>
<div id="shape">
    右鍵獲取任意點的經緯度,座標為:
</div>
</body>
</html>
<script type="text/javascript">
    var map = new BMap.Map("container");
    var pt = new BMap.Point(114.431151,30.468772);
    map.centerAndZoom(pt, 18);
    map.enableScrollWheelZoom();//開啟滾動縮放
    map.enableContinuousZoom();//開啟縮放平滑
    function $(id){
        return document.getElementById(id);
    }
    //繪製範圍
    var pts = [];
    map.addEventListener("rightclick",function(e){
        $("shape").innerHTML=$("shape").innerHTML+" <br/>("+e.point.lng+","+e.point.lat+")";
        var pt = new BMap.Point(e.point.lng,e.point.lat);
        pts.push(pt);
        var ply = new BMap.Polyline(pts, {strokeColor: "red", strokeStyle:"dashed"});
        map.addOverlay(ply);
    });
    //點在多邊形內
    function ptInPolygon(){
        var pt =new BMap.Point(114.431363,30.469658);
        var ply = new BMap.Polygon(pts, {strokeColor: "red", strokeStyle:"dashed"});
        var result = BMapLib.GeoUtils.isPointInPolygon(pt, ply);
        if(result == true){
            alert("點在指定區域內");
        } else {
            alert("點在指定區域外");
        }
        //演示:將面新增到地圖上
        map.clearOverlays();
        var mkr = new BMap.Marker(pt);
        map.addOverlay(mkr);
        map.addOverlay(ply);
    }
    function clearPolygon() {
        $("shape").innerHTML = "";
        pts.length = 0;
        map.clearOverlays();
    }
</script>

效果如圖:

這裡寫圖片描述

相關文章