在項目中愈來愈多的用到了手機的GRS定位功能,使用百度地圖API獲取當前位置並在地圖上標註出來首先應該在官網上註冊key javascript
點擊獲取密鑰,註冊獲取key。
完整代碼以下:html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的key值"></script> <title>百度地圖的定位</title> </head> <body> <div id="allmap" style="width: 100%;height: 500px;"></div> <script type="text/javascript"> // 百度地圖API功能 var map = new BMap.Map("allmap"); var point = new BMap.Point(108.95,34.27); map.centerAndZoom(point,12); var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function(r){console.log(r.point) if(this.getStatus() == BMAP_STATUS_SUCCESS){ var mk = new BMap.Marker(r.point); map.addOverlay(mk);//標出所在地 map.panTo(r.point);//地圖中心移動 //alert('您的位置:'+r.point.lng+','+r.point.lat); var point = new BMap.Point(r.point.lng,r.point.lat);//用所定位的經緯度查找所在地省市街道等信息 var gc = new BMap.Geocoder(); gc.getLocation(point, function(rs){ var addComp = rs.addressComponents; console.log(rs.address);//地址信息 alert(rs.address);//彈出所在地址 }); }else { alert('failed'+this.getStatus()); } },{enableHighAccuracy: true}) </script> </body> </html>
運行結果是: java
(注:用瀏覽器定位是不許確的,建議用手機進行測試!)api