html5中的GPS定位功能主要用的是getCurrentPosition,該方法封裝在 navigator.geolocation 屬性里,是 navigator.geolocation 對象的方法。
getCurrentPosition()函數(shù)簡介
getCurrentPosition(successCallback,errorCallback,positionOptions)
successCallback
表示調(diào)用getCurrentPosition函數(shù)成功以后的回調(diào)函數(shù)刃鳄,該函數(shù)帶有一個參數(shù)苦锨,對象字面量格式位岔,表示獲取到的用戶位置數(shù)據(jù)谤专。該對象包含兩個屬性 coords 和 timestamp校赤。其中 coords 屬性包含以下7個值:
accuracy:精確度
latitude:緯度
longitude:經(jīng)度
altitude:海拔
altitudeAcuracy:海拔高度的精確度
heading:朝向
speed:速度
errorCallback
和 successCallback 函數(shù)一樣帶有一個參數(shù)吆玖,對象字面量格式,表示返回的錯誤代碼马篮。它包含以下兩個屬性:
1沾乘、message:錯誤信息
2、 code:錯誤代碼浑测。
其中錯誤代碼包括以下四個值:
1翅阵、UNKNOW_ERROR:表示不包括在其它錯誤代碼中的錯誤,這里可以在 message 中查找錯誤信息
2、PERMISSION_DENIED:表示用戶拒絕瀏覽器獲取位置信息的請求
3掷匠、 POSITION_UNAVALIABLE:表示網(wǎng)絡不可用或者連接不到衛(wèi)星
4读慎、TIMEOUT:表示獲取超時。必須在options中指定了timeout值時才有可能發(fā)生這種錯誤
positionOptions
positionOptions 的數(shù)據(jù)格式為JSON槐雾,有三個可選的屬性:
1、enableHighAcuracy — 布爾值: 表示是否啟用高精確度模式幅狮,如果啟用這種模式募强,瀏覽器在獲取位置信息時可能需要耗費更多的時間。
2崇摄、timeout — 整數(shù): 表示瀏覽需要在指定的時間內(nèi)獲取位置信息擎值,否則觸發(fā)errorCallback。
3逐抑、maximumAge — 整數(shù)/常量: 表示瀏覽器重新獲取位置信息的時間間隔鸠儿。
getCurrentPosition()函數(shù)定位應用
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
}else{
alert("Sorry, browser does not support geolocation!");
}
}
</script>
</head>
<html>
<body>
<form>
<input type="button" onclick="getLocation();" value="Get Location"/>
</form>
</body>
</html>
點擊按鈕,就可以回提示是否獲取當前位置厕氨,允許之后进每,可以獲取你所在位置的經(jīng)緯度!