HTML5 Geolocation(地理定位)
HTML5 Geolocation API用於獲得使用者的地理位置。
注意:鑑於該特性可能會侵犯使用者的隱私,除非使用者同意,否則使用者位置資訊是不可用的,在使用該功能的時候瀏覽器會彈出提醒框。
#一、地理定位的幾種方式
#IP位址、GPS、Wifi、GSM/CDMA
二、地理位置取得流程
1、使用者開啟需要取得地理位置的web應(yīng)用。
2、應(yīng)用程式向瀏覽器要求地理位置,瀏覽器彈出詢問,詢問使用者是否共用地理位置。
3、假設(shè)使用者允許,瀏覽器從設(shè)別查詢相關(guān)資訊。
4、瀏覽器將相關(guān)資訊傳送到一個信任的位置伺服器,伺服器傳回具體的地理位置。
三、瀏覽器的支援
IE9.0+、FF3.5+、Safari5.0+、Chrome5.0+、Opera10.6 + 支援地理定位。
註解:對於擁有 GPS 的設(shè)備,例如 iPhone(IPhone3.0+、Android2.0+),地理定位更精確。
四、HTML5中地理位置定位的方法
#GeolocationAPI存在於navigator物件中,只包含3個方法:
1、getCurrentPosition //目前位置
2、watchPosition //監(jiān)視位置
3、clearWatch //清除監(jiān)視
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo">點擊按鈕獲取您當前坐標(可能需要比較長的時間獲?。?lt;/p> <button onclick="getLocation()">點我</button> <script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else{x.innerHTML="該瀏覽器不支持獲取地理位置。";} } function showPosition(position) { x.innerHTML="緯度: " + position.coords.latitude + "<br>經(jīng)度: " + position.coords.longitude; } </script> </body> </html>
實例解析:
偵測是否支援地理定位
如果支持,則執(zhí)行g(shù)etCurrentPosition() 方法。如果不支持,則向使用者顯示一段訊息。
如果getCurrentPosition()運作成功,則向參數(shù)showPosition中規(guī)定的函數(shù)傳回coordinates物件
showPosition() 函數(shù)取得並顯示經(jīng)度和緯度
處理錯誤和拒絕
getCurrentPosition() 方法的第二個參數(shù)用於處理錯誤。它規(guī)定當取得使用者位置失敗時運行的函數(shù):
function showError(error)?
{?
????switch(error.code)?
????{?
???????x.innerHTML="用戶拒絕對獲取地理位置的請求。 #????????????break;?
#????????case error.TIMEOUT:?
??????????.innerHTML="請求使用者地理位置逾時。"?
????????????break;?
????????case?
????????????break;?
????}?
}
getCurrentPosition()方法— 傳回資料
若取得位置成功,則getCurrentPosition() 方法返回對象??偸菚骰?latitude、longitude 以及 accuracy 屬性。如果可用,則會傳回其他下面的屬性。
物件#coords.longitude ? ?十進位數(shù)的經(jīng)度? ?
coords.accuracy ? ?位置精確度? ?
coords.altitude ? ?海拔,海平面以上以米計的位置尺寸海拔精準度? ?coords.heading ? ?方向,從正北方開始以度計? ?coords.speed ? ?速度,以公尺/時計? ?
?## 反應(yīng)
##還可以取得地理位置(只有firefox支援)