準備工做javascript
引入百度地圖API和工具類庫前端
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2&ak=您的密鑰"></script> <script type="text/javascript" src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
顯示地圖的HTMLjava
<body> <div style="float:left;width:600px;height:500px;border:1px solid gray" id="container"></div> <div style="float:left;width:300px;height:500px;border:1px solid gray" id="control"> <table style="width:100%;"> <tr> <td colspan="2">判斷是否在區域內:</td> </tr> <tr> <td><input type="button" value="點擊打開範圍" onclick="polygon()" /></td> </tr> <tr> <td>經度<input type="text" value="" id="lng"></td> </tr> <tr> <td>緯度<input type="text" value="" id="lat"></td> </tr> <tr> <td>結果:</td> </tr> <tr> <td><p id="result" style="color:red"></p></td> </tr> </table> </div> </body>
生成多邊形以及判斷點擊的點是否在範圍內的JSapi
<script type="text/javascript"> var map = new BMap.Map("container"); var pt = new BMap.Point(116.404, 39.915); var mkr = new BMap.Marker(pt); var ply; //多邊形 map.centerAndZoom(pt, 16); map.enableScrollWheelZoom(); //開啓滾動縮放 map.enableContinuousZoom(); //開啓縮放平滑 //初始化範圍多邊形 polygon1(); //生成多邊形 function polygon() { var pts = []; var pt1 = new BMap.Point(116.475, 40.017); var pt2 = new BMap.Point(116.355, 40.025); var pt3 = new BMap.Point(116.220, 39.994); var pt4 = new BMap.Point(116.208, 39.888); var pt5 = new BMap.Point(116.279, 39.780); var pt6 = new BMap.Point(116.398, 39.759); var pt7 = new BMap.Point(116.558, 39.846); var pt8 = new BMap.Point(116.549, 39.939); pts.push(pt1); pts.push(pt2); pts.push(pt3); pts.push(pt4); pts.push(pt5); pts.push(pt6); pts.push(pt7); pts.push(pt8); ply = new BMap.Polygon(pts); //演示:將面添加到地圖上 map.clearOverlays(); map.addOverlay(ply); } map.addEventListener("click", function (e) { mkr.setPosition(e.point); map.addOverlay(mkr); //將點擊的點的座標顯示在頁面上 document.getElementById("lng").value = e.point.lng; document.getElementById("lat").value = e.point.lat; InOrOutPolygon(e.point.lng, e.point.lat); }); function InOrOutPolygon(lng, lat){ var pt = new BMap.Point(lng, lat); var result = BMapLib.GeoUtils.isPointInPolygon(pt, ply); if (result == true) { document.getElementById("result").innerHTML = "在區域範圍內"; } else { document.getElementById("result").innerHTML = "在區域範圍外"; } } </script>