地理位置對象能夠用於基於地圖的應用,通常手機的位置信息是經過GPS或者基站來獲取,而pc則是經過IP地址來獲取,準確度沒有移動設備高。git
地理位置對象navigator.geolocation下有有兩個方法,分別是getCurrentPosition()單次定位請求和watchPosition()屢次定位請求。json
1.navigator.geolocation.getCurrentPosition(function(),function(),{});瀏覽器
三個參數依次爲請求成功的回調,失敗的回調,數據收集方式(一個json形式的配置),以下:緩存
timer = navigator.geolocation.getCurrentPosition(function(position){ '經度:' + position.coords.longitude+'\n'; '緯度 :' + position.coords.latitude+'\n'; '準確度 :' + position.coords.accuracy+'\n'; '海拔 :' + position.coords.altitude+'\n'; '海拔準確度 :' + position.coords.altitudeAcuracy+'\n'; '行進方向 :' + position.coords.heading+'\n'; '地面速度 :' + position.coords.speed+'\n'; '時間戳:' + new Date(position.timestamp)+'\n'; },function(err){ //err.code // 失敗所對應的編號 navigator.geolocation.clearWatch(timer); },{ enableHighAcuracy : true, timeout : 5000, maximumAge : 5000, frequency : 1000 });
如上所示:函數
請求成功的函數,接受一個參數,該參數下有一下屬性:spa
經度 : coords.longitudecode
緯度 : coords.latitude對象
準確度 : coords.accuracyblog
海拔 : coords.altitudeget
海拔準確度 : coords.altitudeAcuracy
行進方向 : coords.heading
地面速度 : coords.speed
時間戳 : new Date(position.timestamp)
不過其中有些屬性只有在移動設備纔會存在。
2.、屢次定位請求watchPosition()
用法和getCurrentPosition同樣,不過僅僅只有移動設備,位置改動纔會觸發。
請求失敗的時候,err.code是錯誤編號,分別表示不一樣的錯誤,以下:
code 0 : 不包括其餘錯誤編號中的錯誤
1 : 用戶拒絕瀏覽器獲取位置信息
2 : 嘗試獲取用戶信息,但失敗了
3 : 設置了timeout值,獲取位置超時了
數據收集方式:
enableHighAcuracy : 更精確的查找,默認false
timeout : 獲取位置容許最長時間,默認infinity
maximumAge : 位置能夠緩存的最大時間,默認0
frequency :更新的頻率
這兩個方法的使用相似於定時器,因此也有一個方法clearWatch()用於關閉更新請求。