百度地圖api web獲取當前位置瀏覽器JavaScript定位 javaweb 瀏覽器端
阿新 • • 發佈:2019-01-06
<!doctype html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script> <script src="http://api.map.baidu.com/api?v=2.0&ak=Dc8o3GUube9RVOhmeuuhfNL9QRyzhuaj" type="text/javascript"></script> <title>瀏覽器定位</title> </head> <body> <div> <span id="load_geolocation">點選獲取位置</span> </div> </body> </html> <script type="text/javascript"> $(function(){ $("#load_geolocation").click(function(ev){ $(ev.currentTarget).text("正在獲取位置......"); //建立百度地圖控制元件 var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function(r){ if(this.getStatus() == BMAP_STATUS_SUCCESS){ //以指定的經度與緯度建立一個座標點 var pt = new BMap.Point(r.point.lng,r.point.lat); //建立一個地理位置解析器 var geoc = new BMap.Geocoder(); geoc.getLocation(pt, function(rs){//解析格式:城市,區縣,街道 var addComp = rs.addressComponents; $(ev.currentTarget).text(addComp.city + ", " + addComp.district + ", " + addComp.street); }); } else { $(ev.currentTarget).text('定位失敗'); } },{enableHighAccuracy: true})//指示瀏覽器獲取高精度的位置,預設false }); }); </script>