一、簡介
html5為window.navigator提供了geolocation屬性,用于獲取基于瀏覽器的當(dāng)前用戶地理位置。
window.navigator.geolocation提供了3個(gè)方法分別是:
void getCurrentPosition(onSuccess,onError,options); //獲取用戶當(dāng)前位置 int watchCurrentPosition(onSuccess,onError,options); //持續(xù)獲取當(dāng)前用戶位置 void clearWatch(watchId); //watchId 為watchCurrentPosition返回的值 //取消監(jiān)控 options = { enableHighAccuracy,//boolean 是否要求高精度的地理信息 timeout,//獲取信息的超時(shí)限制 maximumAge//對(duì)地理信息進(jìn)行緩存的時(shí)間 } //options可以不寫,為默認(rèn)即可
二、position對(duì)象
當(dāng)成功獲取地理位置信息時(shí)候,onsuccess方法中會(huì)返回position對(duì)象,通過這個(gè)對(duì)象可以獲取地理位置的相關(guān)信息,包括:
position對(duì)象的屬性: latitude,//緯度 longitude,//經(jīng)度 altitude,//海拔高度 accuracy,//獲取緯度或者經(jīng)度的精度 altitudeAccurancy,//海拔高度的精度 heading,//設(shè)備前景方向。正北方向的順時(shí)針旋轉(zhuǎn)角 speed,//設(shè)備的前進(jìn)速度 m/s timestamp,//獲取地理位置信息時(shí)候的時(shí)間
三、基于google map的例子
直接看代碼:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>在頁面上使用google地圖示例</title> </head> <body onload = 'init()'> <div id="map" style='width:800px;height:800px;'></div> <script type="text/javascript" src='http://maps.google.com/maps/api/js?sensor=false'></script> <script type="text/javascript"> function init(){ if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(pos){ var coords = pos.coords; var latlng =new google.maps.LatLng(coords.latitude,coords.longitude); var options = {zoom:14,center:latlng,mapTypeId : google.maps.MapTypeId.ROADMAP}; var map1; map1 =new google.maps.Map(document.getElementById('map'),options); var marker =new google.maps.Marker({ position : latlng, map : map1 }); var infowindow =new google.maps.InfoWindow({ content : '當(dāng)前位置!' }); infowindow.open(map1,marker); }); } } </script> </body> </html>