在HTML5中,加入了新的地理位置API用來確定和分享地理位置。
隱私申明
在與遠程Web伺服器共用物理位置時,隱私是一個需要關注的問題。因此,地理位置API會要求使用者先提供許可權,然後Web應用程式才能訪問位置資訊。首次訪問請求地理位置資料的網頁時,瀏覽器將顯示一個通知欄,提示提供對使用者位置的存取權限。按照瀏覽器的提示,選擇相關的授權即可。
如果使用者未授予許可權,則不會向 Web 應用程式提供位置資訊。調用相關API不會觸發成功回調。
檢查瀏覽器的支援情況
地理位置API在主流的瀏覽器的最新版中都支援了,但是為了相容老的瀏覽器,還是要檢查一下。如果地理位置 API 不可用,則 window.navigator.geolocation 將為 null,如下所示:
| 代碼如下 |
複製代碼 |
function show_islocationenabled()
{
var str = "No, geolocation is not supported.";
if (window.navigator.geolocation) {
str = "Yes, geolocation is supported.";
}
alert( str );
}
|
Geolocation API基於navigator這一全域對象的一個新屬性:navigator.geolocation,該對象提供了一些關於訪問者的瀏覽器和系統的有用資訊。Geolocation的資訊可以通過許多手段獲得:比如基站、web的資料庫或是GPS等。使用不同的方式擷取到的Geolocation資訊精度也是不一樣的,通常情況下,通過GPS獲得的最為準確(移動平台上使用GPS最多,PC平台上基本都是靠網路資料)。偶然情況下,在一些位置上,你有可能不能獲得明確的地理位置讀數或是一點資料都接收不到。
定位當前位置
使用navigator.geolocation的getCurrentPosition()方法擷取使用者的當前位置,這個方法只擷取一次位置的資訊。當該方法被指令碼調用時,方法以非同步方式來嘗試擷取宿主裝置的當前位置。
方法簽名:getCurrentPosition(geolocationSuccessCallback,[geolocationErrorCallback,geolocationOptions]);
geolocationSuccessCallback:擷取當前位置成功後的回調(必需的)
geolocationErrorCallback. 有錯誤發生時使用的回調(可選的)
geolocationOptions. 地理位置選項(可選的)
處理位置資訊
getCurrentPositon()方法獲得當前位置成功後會將位置資訊儲存到一個Position對象中,然後把這個對象作為參數來執行geolocationSuccessCallback這一回調。在這個回呼函數中,你可以任意處置這個對象中包含的資訊。
Position對象有兩個屬性:timestamp和coords。timestamp屬性工作表示地理位置資料的建立時間,coords屬性工作表示地理位置資訊,又包含七個屬性:
coords.latitude:估計緯度
coords.longitude:估計經度
coords.altitude:估計高度
coords.accuracy:所提供的以米為單位的經度和緯度估計的精確度
coords.altitudeAccuracy:所提供的以米為單位的高度估計的精確度
coords.heading: 宿主裝置當前移動的角度方向,相對於正北方向順時針計算
coords.speed:以米每秒為單位的裝置的當前對地速度
一般的,這些屬性中有三項是保證有的:coords.latitude、coords.longitude和coords.accuracy,其餘的返回null;這取決於裝置的能力和其所採用的後端定位服務器。而且,heading和speed屬性可以基於使用者之前的位置計算出來。
處理錯誤
執行getCurrentPositon()方法時如果有錯誤發生的話,則該方法傳遞一個PositionError對象給geolocationErrorCallback回調。
設定地理位置選項
你可以設定geolocationOptions的三個屬性:
enableHighAccuracy:如果裝置支援高精度的話,這個選項表示是否啟用高精度。
timeout:查詢逾時時間
maximumAge: 緩衝的位置最大的時間數,在這一時間段內緩衝可被使用。 看下面完整的例子:
| 代碼如下 |
複製代碼 |
|
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position:</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script>
var x=document.getElementById("demo");
function getLocation() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon=position.coords.latitude+","+position.coords.longitude;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" +
latlon + "&zoom=9&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' />";
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred."
break;
}
}
</script>
</body>
</html>
|
這個例子擷取到當前裝置所在的地理位置並顯示到Google地圖中。當然你可以使用百度地圖API中的靜態圖版來改造這個例子。百度地圖API參看後面的實用參考中的連結。
開啟/取消持續定位
使用navigator.geolocation的watchPosition()方法可以定期輪詢使用者的位置,查看使用者的位置是否發生改變。這個方法有三個參數:這三個參數和getCurrentPosition()方法一樣,一個成功後的回調,一個失敗後的回調,和一個擷取位置資訊的選項;這個方法有一個傳回值watchID,用於取消持續定位。
使用navigator.geolocation的clearWatch()方法可以終止進行中的watchPosition(),該方法只帶一個參數watchID。
看下面的例子:
| 代碼如下 |
複製代碼 |
|
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API Example: Listening for Location Updates</title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript">
function setText(val, e) {
document.getElementById(e).value = val;
}
var nav = null;
var watchID;
function listenForPositionUpdates() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
watchID = geoloc.watchPosition(successCallback);
}
else {
alert("geolocation not supported");
}
}
else {
alert("Navigator not found");
}
}
function clearWatch(watchID) {
window.navigator.geolocation.clearWatch(watchID);
}
function successCallback(position)
{
setText(position.coords.latitude, "latitude");
setText(position.coords.longitude, "longitude");
}
</script>
</head>
<body>
<label for="latitude">Latitude: </label><input id="latitude" /> <br />
<label for="longitude">Longitude: </label><input id="longitude" /> <br />
<input type="button" value="Watch Latitude and Longitude" onclick="listenForPositionUpdates()" />
<input type="button" value="Clear watch" onclick="clearWatch()" />
</body>
</html>
|