1.navigator.geolocation
HTML5中的地理位置相關的主要對象是navigator.geolocation,它有一些方法和屬性,檢測瀏覽器對HTML5地理位置的支援性也就是檢測該對象。
2.getCurrentPosition、watchPosition和clearWatch方法
這是geolocation的兩個核心方法。第一個方法只擷取地理位置資訊,後一個方法以一定時間間隔擷取地理位置資訊,它們的參數相同,但傳回值不同,後者返回一個watchId,將watchId作為參數傳遞給clearWatch方法可以終止對地理位置資訊的請求。
getCurrentPosition形如:
void getCurrentPosition(in PositionCallback successCallback,
in optional PositionErrorCallback errorCallback,
in optional PositionOptions options);
第一個參數是一個函數,用於處理成功接收到的地理位置資訊,它通常接收一個position對象作為參數,並提供接收到的地理位置資訊。
第二格參數是可選的,也是一個函數,用於錯誤處理,該函數通常接收一個error對象作為參數,error含有錯誤資訊。
第三個參數用於進一步控制地理位置資訊,也是可選的。它通常用花括弧括起來,它通常有三個值:
enableHighAccuracy:用於控制精度,它的效果可能會有副作用。
timeout:用於指定地理位置資訊請求的逾時時間,單位是毫秒。
maximumAge:用於指定地理位置資訊的更新頻率,單位是毫秒。
一個樣本如下:
navigator.geolocation.getCurrentPosition(updateLocation,handleLocationError,
{timeout:10000});
3.psition對象
其定義如下:
interface Position {
readonly attribute Coordinates coords;
readonly attribute DOMTimeStamp timestamp;
};
它有一個子物件coords和一個屬性timestamp。
coords:是一個Coordinates對象,其定義如下:
interface Coordinates {
readonly attribute double latitude; //維度
readonly attribute double longitude; //經度
readonly attribute double? altitude; //高程(/m)
readonly attribute double accuracy; //經度和維度精確度(/m)
readonly attribute double? altitudeAccuracy; //高程精確度(/m)
readonly attribute double? heading; //移動方向(/deg)
readonly attribute double? speed; //移動速度(/m/s)
};
其中帶問號的屬性在許多瀏覽器和裝置中不會實現,如果沒有這些屬性,通過編程 擷取的值將是null。
latitude,longitude和accuracy三個屬性,分別用於提供請求到的維度,經度和精 度資訊。經緯度用小數表示,精度單位是米。
timestamp:時間戳記。
4.error對象
error對象有一個code屬性,用於指定錯誤類型,可以認為code是一個枚舉類型,它有四個值:0(UNKNOWN_ERROR1,1(PERMISSION_DENIED),2(POSITION_UNAVAILABLE)和
3(TIMEOUT)。
另外,error還有一個message屬性,用於提供錯誤的詳細資料。