位置信息從何而來
設備可以使用下列數據源
- IP地址
- 三維坐標:GPS(Global Positioning System,全球定位系統);從RFID、Wi-Fi和藍牙到Wi-Fi的MAC地址;GSM或CDMA手機的ID
- 用戶自定義的數據
瀏覽器支持性檢查
<div> <span class="info"> <p id="status"></p> </span> </div> <script type="text/javascript"> if (navigator.geolocation) { document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser."; } else { document.getElementById("status").innerHTML = "HTML5 Geolocation is not supported in your browser."; } </script>
位置請求
單次定位請求函數:void getCurrentPosition(in PositionCallback successCallBack,in optional PositionErrorCallback errorCallback,
in optional PositionOptios options)
這個函數是通過navigator.geolocation對象來調用的,所以在腳本中需要先取得此對象。這個函數接受一個必選參數和兩個可選參數。
- successCallBack:為瀏覽器指明位置數據可用時應調用的函數,即收到實際位置信息並進行處理的地方。
- errorCallback:出錯處理
- options:用來調整HTML5 Geolocation服務的數據收集方式。
示例
navigator.geolocation.getCurrentPosition(updateLocation,handleeLocationError);
這里updateLocation就是接收位置信息並進行重的函數,handleeLocationError是進行錯誤處理的函數。
updateLocation()函數
updateLocation只接受一個參數:位置對象。這個對象包含坐標(coords特性)和一個獲取位置數據時的時間戳。以下是坐標的主要特性:
- latitude(緯度)
- longitude(經度)
- accuracy(准確度)
function updateLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; if (!latitude || !longitude) { document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser, but location is currently not available."; return; } document.getElementById("latitude").innerHTML = latitude; document.getElementById("longitude").innerHTML = longitude; }
handleeLocationError()函數
HTML5定義了一些錯誤編號:
- PERMISSION_DENIED(錯誤編號為1)——用戶選擇拒絕瀏覽器獲得其位置信息。
- POSITION_UNAVAILABLE(錯誤編號為2)——嘗試獲取用戶位置數據失敗。
- TIMEOUT(錯誤編號為3)——設置了可選的timeout值,獲取用戶位置超時。
function handleeLocationError(error) { switch (error.code) { case 0: alert(error.message); break; case 1: alert(error.message); break; case 2: alert(error.message); break; case 3: alert(error.message); break; } }
options:可選的地理定位請求特性
enableHighAccuracy:如果啟用該參數,則通知瀏覽器啟用HTML5 Geolocation服務的高精度模式,參數的默認值為false.
timeout:可選值,單位為ms,告訴瀏覽器計算當前位置所允許的最長時間。默認值為Infinity,即為無窮大或無限制。
maximumAge:這個值表示瀏覽器重新計算位置的時間間隔。它也是一個以ms為單位的值,默認為零,這意味着瀏覽器每次請求時必須立即重新計算位置。
這三個參數可以使用JSON對象傳遞,這樣更便於添加到HTML5 Geolocation請求調用中。
navigator.geolocation.getCurrentPosition(updateLocation, handleeLocationError, {timeout:10000});
重復性的位置更新請求
navigator.geolocation.watchPosition(updateLocation,handleLocationError);
這個函數只要用戶位置發生變化,Geolocation服務就會調用updateLocation處理程序。它的效果就像是在監視用戶的位置,並會在其變化時及時通知用戶一樣。
關閉函數
如果程序不再需要接收用戶的位置信息,則可以調用
navigator.geolocation.clearWatch(watchId)
//持續更新位置信息 var watchId = navigator.geolocation.watchPosition(updateLocation, handleeLocationError); //停止更新 navigator.geolocation.clearWatch(watchId);
使用HTML5 Geolocation構建應用
這里我們使用多次請求特性構建一個簡單有用的WEB應用程序——距離跟蹤器,通過些應用程序可以了解到HTML5 Geolocation AIP的強大之處。
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>HTML5 Geolocation Odometer</title> <link rel="stylesheet" href="styles.css"> </head> <body onload="loadDemo()"> <h1>HTML5 Geolocation Distance Tracker</h1> <p id="status">HTML5 Geolocation is <strong>not</strong> supported in your browser.</p> <h2>Current Position:</h2> <table border="1"> <tr> <th width="40" scope="col"><h5>Latitude</h5></th> <td width="114" id="latitude">?</td> </tr> <tr> <td> Longitude</td> <td id="longitude">?</td> </tr> <tr> <td>Accuracy</td> <td id="accuracy">?</td> </tr> <tr> <td>Last Timestamp</td> <td id="timestamp">?</td> </tr> </table> <h4 id="currDist">Current distance traveled: 0.0 km</h4> <h4 id="totalDist">Total distance traveled: 0.0 km</h4> <script type="text/javascript"> var totalDistance = 0.0; var lastLat; var lastLong; Number.prototype.toRadians = function() { return this * Math.PI / 180; } function distance(latitude1, longitude1, latitude2, longitude2) { // R is the radius of the earth in kilometers var R = 6371; var deltaLatitude = (latitude2-latitude1).toRadians(); var deltaLongitude = (longitude2-longitude1).toRadians(); latitude1 = latitude1.toRadians(), latitude2 = latitude2.toRadians(); var a = Math.sin(deltaLatitude/2) * Math.sin(deltaLatitude/2) + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(deltaLongitude/2) * Math.sin(deltaLongitude/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; return d; } function updateStatus(message) { document.getElementById("status").innerHTML = message; } function loadDemo() { if(navigator.geolocation) { updateStatus("HTML5 Geolocation is supported in your browser."); navigator.geolocation.watchPosition(updateLocation, handleLocationError, {maximumAge:20000}); } } function updateLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var accuracy = position.coords.accuracy; var timestamp = position.timestamp; document.getElementById("latitude").innerHTML = latitude; document.getElementById("longitude").innerHTML = longitude; document.getElementById("accuracy").innerHTML = accuracy; document.getElementById("timestamp").innerHTML = timestamp; // sanity test... don't calculate distance if accuracy // value too large if (accuracy >= 500) { updateStatus("Need more accurate values to calculate distance."); return; } // calculate distance if ((lastLat != null) && (lastLong != null)) { var currentDistance = distance(latitude, longitude, lastLat, lastLong); document.getElementById("currDist").innerHTML = "Current distance traveled: " + currentDistance.toFixed(4) + " km"; totalDistance += currentDistance; document.getElementById("totalDist").innerHTML = "Total distance traveled: " + currentDistance.toFixed(4) + " km"; } lastLat = latitude; lastLong = longitude; updateStatus("Location successfully updated."); } function handleLocationError(error) { switch(error.code) { case 0: updateStatus("There was an error while retrieving your location: " + error.message); break; case 1: updateStatus("The user prevented this page from retrieving a location."); break; case 2: updateStatus("The browser was unable to determine your location: " + error.message); break; case 3: updateStatus("The browser timed out before retrieving the location."); break; } } </script> </body> </html>
在Google Map上顯示“我在這里”
<div id="map"></div> <script src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> var map = new google.maps.Map(document.getElementById("map")); function updateLocation(position) { map.setCenter(new google.maps.LatLng(parseFloat(position.coords.latitude), parseFloat(position.coords.longitude))); } navigator.geolocation.getCurrentPosition(updateLocation); </script>