地理位置對象可以用於基於地圖的應用,一般手機的位置信息是通過GPS或者基站來獲取,而pc則是通過IP地址來獲取,准確度沒有移動設備高。
地理位置對象navigator.geolocation下有有兩個方法,分別是getCurrentPosition()單次定位請求和watchPosition()多次定位請求。
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 });
如上所示:
請求成功的函數,接受一個參數,該參數下有一下屬性:
經度 : coords.longitude
緯度 : coords.latitude
准確度 : coords.accuracy
海拔 : coords.altitude
海拔准確度 : 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()用於關閉更新請求。