HTML5 Geolocation API 用於獲得用戶的地理位置。
如果用戶不允許定位,那么用戶信息是不可用的。
獲取用戶的位置:getCurrentPosition() 返回數據如下
返回用戶當前位置: watchPosition()
返回用戶的當前位置,並繼續返回用戶移動時的更新位置。也可使用setinterval()自定義時間執行一次定位函數。
clearWatch()用於停止 watchPosition() 方法
<!DOCTYPE html> <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://api.map.baidu.com/api?v=2.0&ak=你的key"></script> <title>定位</title> </head> <body> <h1>Html5定位</h1> <p id="longitude"></p><!-- 經度值 --> <p id="latitude"></p><!-- 緯度值 --> <p id="accuracy"></p><!-- 誤差值 --> <!--<input type="button" value="創建地圖" onclick="creatMap()">--> <div style="width:370px;height:550px;border:#ccc solid 1px;" id="dituContent"></div><!-- 地圖容器 --> <script src="jquery-1.11.3.js"></script> <script> //如果支持,獲取位置信息 if(navigator.geolocation){ navigator.geolocation.getCurrentPosition( //locationSuccess function(position){ showPosition(position);//顯示經緯度值 creatMap();//創建地圖 }, //locationError function(error){ var errorType = ['您拒絕共享位置信息', '獲取不到位置信息', '獲取位置信息超時']; alert(errorType[error.code - 1]); } ); navigator.geolocation.watchPosition(showPosition); }else{ //document.getElementById('geo_loc').innerHTML="您的瀏覽器不支持地圖定位"; $('#geo_loc').html("您的瀏覽器不支持地圖定位") } function showPosition(position){ //在頁面上顯示經緯度(此處顯示的是getLocation獲得的經緯度值) $('#longitude').html(position.coords.longitude) $('#latitude').html(position.coords.latitude) //顯示誤差值 $('#accuracy').html("誤差"+position.coords.accuracy) } function creatMap(){ var localLongitude = $('#longitude').text();//getLocation得到的經緯度值 var localLatitude = $('#latitude').text(); //根據getLocation得到的經緯度坐標直接創建地圖,有很大誤差,需要轉換為百度的經緯度坐標。
//請求百度接口轉換坐標 var newpoit = 'http://api.map.baidu.com/geoconv/v1/?coords='+localLongitude+','+localLatitude+'&from=1&to=5&ak=你的key'; $.ajax({ type:"POST", async:false, url:newpoit, dataType:"jsonp", success:function(data){ if(parseInt(data.status)==0){//請求成功 $.each(data.result,function(i,item){ //獲轉換后的經緯度 var baiduLongitude = item.x; var baiduLatitude = item.y; //創建地圖 var map = new BMap.Map("dituContent"); map.centerAndZoom(new BMap.Point(baiduLongitude,baiduLatitude),15); map.enableScrollWheelZoom(true); var new_point = new BMap.Point(baiduLongitude,baiduLatitude); var marker = new BMap.Marker(new_point); // 創建標注 map.addOverlay(marker); // 將標注添加到地圖中 map.panTo(new_point); }) } }, error:function(e){ } }) } </script> </body> </html>