准备工作
- 注册开发者
- 创建应用
- 拿到百度地图ak
前端实现方案
引入百度地图API和工具类库
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script> <script type="text/javascript" src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
显示地图的HTML
<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>
生成多边形以及判断点击的点是否在范围内的JS
<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>
原文地址:https://www.cnblogs.com/meng-ma-blogs/p/9318439.html
时间: 2024-11-04 12:54:51