HTML5 Geolocation(地理定位)
HTML5 Geolocation API用于獲得用戶的地理位置。
注意:鑒于該特性可能侵犯用戶的隱私,除非用戶同意,否則用戶位置信息是不可用的,在使用該功能的時候瀏覽器會彈出提醒框。
一、地理定位的幾種方式
IP地址、GPS、Wifi、GSM/CDMA
二、地理位置獲取流程
1、用戶打開需要獲取地理位置的web應用。
2、應用向瀏覽器請求地理位置,瀏覽器彈出詢問,詢問用戶是否共享地理位置。
3、假設用戶允許,瀏覽器從設別查詢相關信息。
4、瀏覽器將相關信息發(fā)送到一個信任的位置服務器,服務器返回具體的地理位置。
三、瀏覽器的支持
IE9.0+、FF3.5+、Safari5.0+、Chrome5.0+、Opera10.6+ 支持地理定位。
注釋:對于擁有 GPS 的設備,比如 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">點擊按鈕獲取您當前坐標(可能需要比較長的時間獲取):</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>
實例解析:
檢測是否支持地理定位
如果支持,則運行 getCurrentPosition() 方法。如果不支持,則向用戶顯示一段消息。
如果getCurrentPosition()運行成功,則向參數(shù)showPosition中規(guī)定的函數(shù)返回一個coordinates對象
showPosition() 函數(shù)獲得并顯示經(jīng)度和緯度
處理錯誤和拒絕
getCurrentPosition() 方法的第二個參數(shù)用于處理錯誤。它規(guī)定當獲取用戶位置失敗時運行的函數(shù):
function showError(error)?
{?
????switch(error.code)?
????{?
????????case error.PERMISSION_DENIED:?
????????????x.innerHTML="用戶拒絕對獲取地理位置的請求。"?
????????????break;?
????????case error.POSITION_UNAVAILABLE:?
????????????x.innerHTML="位置信息是不可用的。"?
????????????break;?
????????case error.TIMEOUT:?
????????????x.innerHTML="請求用戶地理位置超時。"?
????????????break;?
????????case error.UNKNOWN_ERROR:?
????????????x.innerHTML="未知錯誤。"?
????????????break;?
????}?
}
getCurrentPosition()方法 — 返回數(shù)據(jù)
若獲取位置成功,則 getCurrentPosition() 方法返回對象。始終會返回 latitude、longitude 以及 accuracy 屬性。如果可用,則會返回其他下面的屬性。
屬性 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??描述
coords.latitude ? ?十進制數(shù)的緯度 ? ?
coords.longitude ? ?十進制數(shù)的經(jīng)度 ? ?
coords.accuracy ? ?位置精度 ? ?
coords.altitude ? ?海拔,海平面以上以米計 ? ?
coords.altitudeAccuracy ? ?位置的海拔精度 ? ?
coords.heading ? ?方向,從正北開始以度計 ? ?
coords.speed ? ?速度,以米/每秒計 ? ?
timestamp ? ?響應的日期/時間 ? ?
還可以獲得地理位置(只有firefox支持)
p.address.country 國家
p.address.region 省份
p.address.city 城市