项目需求
- 根据手机端GPS自动获取实时定位;
- 单击定位控件,筛选当前中心点坐标范围内关键词和距离符合条件的所有标注点;
- 关键词和半径可以自定义选择;
- PC端通过IP获取定位的方式,对浏览器有一定的要求。
项目说明
- 实时定位,需要https加密证书的支持,否则,F12控制台会出现黄色的警示。
getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.
- 首次加载定位和定位控件,在实际开发中,是两次不同的事件,需要封装函数,重复使用。
项目开发
jsAPI接口引入
<script type="text/javascript"src="https://api.map.baidu.com/getscript?v=3.0&ak=3HGqGo1RHf8zsLZCMj3Fz**"></script>
构建地图容器
<div class="radius"> <select name="keyword" id="keyword"> <option value="餐馆">餐馆</option> <option value="医院">医院</option> <option value="酒店">酒店</option> <option value="学校">学校</option> </select> <select name="radius" id="radius"> <option value="3000">3km</option> <option value="5000">5km</option> <option value="10000">10km</option> </select> </div> <div id="lock_map"></div>
CSS样式表
<style> html, body { margin: 0; padding: 0; width: 100%; height: 100%; } #lock_map { width: 100%; height: 100%; margin: 0; padding: 0; } .radius { position: absolute; z-index: 9999; right: 10px; }
初始化地图
var map = new BMap.Map("lock_map"); var point = new BMap.Point(117.016415, 36.619618); map.centerAndZoom(point, 12); map.enableScrollWheelZoom(true); // 添加定位控件; var geolocationControl = new BMap.GeolocationControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT });
定位控件事件监听
geolocationControl.addEventListener("locationSuccess", function (e) { getGEO(); }); map.addControl(geolocationControl);
定位函数
//定位; function getGEO(){ var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function (r) { if (this.getStatus() == BMAP_STATUS_SUCCESS) { map.clearOverlays(); //返回当前中心点; map.panTo(r.point); map.centerAndZoom(r.point, 14); //获取半径; var radiusLength = $("#radius").val(); var keyword = $("#keyword").val(); console.log(keyword) var x = r.point.lng; var y = r.point.lat; var newPoint = new BMap.Point(x, y); addMaker(newPoint);//标注中心; addCircle(newPoint, radiusLength);//范围; searchMaker(newPoint, keyword, x, y);//周边标注; } else { alert('failed' + this.getStatus()); } }, function (error) { console.log(error); }, { enableHighAccuracy: true, timeout: 1000, maximumAge: 0 }); }
添加标注
//添加标注; function addMaker(point) { var marker = new BMap.Marker(point); map.addOverlay(marker); }
添加圆形覆盖物
//添加圆形覆盖物; function addCircle(newPoint, radius) { var circle = new BMap.Circle(newPoint, radius, { fillColor: 'blue', fillOpacity: 0.3, strokeColor: 'blue', strokeWeight: 1, strokeOpacity: 0.5 }); map.addOverlay(circle); }
搜索周边坐标
//搜索周边坐标; function searchMaker(newPoint, keyword, x, y) { //后台数据库,返回范围内的数据经纬度即可; var local = new BMap.LocalSearch(map, {renderOptions: {map: map, autoViewport: false}}); local.searchNearby(keyword, newPoint, 1000); console.log("中心经纬度:" + x + "," + y); }
@lockdata.cn