天天看點

移動Web應用程式開發HTML5篇 (五) 地理位置API

1. 地理位置API介紹

地位位置(Geolocation) API是HTML5引入的一個非常誘人的API,它在移動web應用的開發中非常有價值。隻需要幾行很簡單的代碼即可實作擷取使用者的地位位置。目前浏覽器對其支援情況如下圖:

移動Web應用程式開發HTML5篇 (五) 地理位置API

HTML5的地理位置API依次通過以下幾個方式擷取位置資訊:1. IP位址,2. GPS定位,3. MAC位址,4. GSM基站網絡,5. 使用者定義的位址位置。如下圖所示,優先級為逆時鐘方向。

移動Web應用程式開發HTML5篇 (五) 地理位置API

2. 使用地理位置API

地位位置(Geolocation) API使用非常友善,一個典型的判斷浏覽器是否支援HTML5 Geolocation API的函數:

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;
    }           

在這段代碼中,使用

var latitude = position.coords.latitude;

var longitude = position.coords.longitude;

這兩個變量來儲存經度和緯度,并将其傳回給HTML代碼,本例的其餘代碼如下所示:

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>HTML5 Geolocation</title>
    <link rel="stylesheet" href="styles.css" target="_blank" rel="external nofollow" >
</head>

<body οnlοad="loadDemo()">

<h1>HTML5 Geolocation Example</h1>

<span class="info">
  <p id="status">HTML5 Geolocation is <strong>not</strong> supported in your browser.</p>
</span>

<h2>Current Position:</h2>
<table border="1">
          <tr>
            <th width="40" scope="col"><h5 align="left">Lat.</h5></th>
             <td width="114" id="latitude">?</td>
          </tr>
          <tr>
            <td><h5>Long.</h5></td>
            <td id="longitude">?</td>
          </tr>
          <tr>
            <td><h5>Time</h5></td>
            <td id="longitude2">11:00:00 a.m.</td>
          </tr>
</table>

<p align="center" class="style2">Copyright (c) 2010</p>

<script type="text/javascript">

    function loadDemo() {
        if(navigator.geolocation) {
            document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser.";
            navigator.geolocation.getCurrentPosition(updateLocation);
        }
    }           

其運作結果如下圖:

移動Web應用程式開發HTML5篇 (五) 地理位置API

同樣可以将經度緯度指派給相應google map的api,得出下圖所示的結果:

移動Web應用程式開發HTML5篇 (五) 地理位置API

3.地理位置API擷取流程

相信很多人會問地位位置(Geolocation) API使用的确非常友善,但是也太危險了,使用者如何知道哪個應用程式在擷取我的位置資訊呢?使用者如何進行權限設定呢。

移動Web應用程式開發HTML5篇 (五) 地理位置API

圖中标出的1, 2, 3 ,4 分别表示:

1. 表明一個使用者試圖打開一個調用地理位置資訊的應用程式

2. 正常情況下,應用程式通過地位位置函數擷取位置資訊就可以了,但是浏覽器會在這個地方将其中斷,并請求使用者授權,如果通過,則調用該函數,否則傳回permission denied。

3. 浏覽器根據上文所述的優先級依次擷取裝置相關資訊,如果IP 位址,GPS資訊等等,這是浏覽器内部的行為。

4. 浏覽器将坐标資訊發送給外部的可信任的位置服務提供商哪裡,如google map,位置服務提供商傳回該位置的具體資訊。

4. 地理位置API 例子

這是一個稍微複雜一點的例子,這個例子主要實作一個實時HTML5定位系統,主要代碼如下:

<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>           

完整代碼下載下傳位址:

下載下傳

繼續閱讀