---
title: 地理位置定位 (Geolocation)
slug: Web/API/Geolocation_API
translation_of: Web/API/Geolocation_API
original_slug: Web/API/Geolocation/Using_geolocation
---
<p>Web Apps 若需要使用者的位置,可透過<strong> Geolocation API</strong> 取得相關資訊。而基於隱私權的考量,這些 Web Apps 均必須取得使用者的許可之後,才能發佈位置資訊。</p>

<h2 id="地理位置定位_Geolocation_物件">地理位置定位 (Geolocation) 物件</h2>

<p>Geolocation API,是透過 <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation" title="The documentation about this has not yet been written; please consider contributing!"><code>navigator.geolocation</code></a> <code>物件</code>所發佈。</p>

<p>若該物件可用,即可進行地理位置定位服務。因此可先測試地理位置定位是否存在:</p>

<pre class="brush: js">if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}
</pre>

<div class="note"><strong>注意:</strong>在 Firefox 24 之後的版本,即使停用此 API,<code>navigator </code>中的「<code>geolocation」也同樣回傳</code> <code>true。此問題已根據規格而於</code> <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/25/Site_Compatibility">Firefox 25</a> 中修正 (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=884921" title="FIXED: Align navigator.geolocation with spec">bug 884921</a>)。</div>

<h3 id="取得目前位置">取得目前位置</h3>

<p>若要取得使用者目前的位置,可呼叫 <code>getCurrentPosition()</code> 函式。如此將啟動非同步化的請求,以偵測使用者的位置,並將查詢定位硬體而取得最新資訊。一旦決定位置,隨即執行特定的回呼常式 (Callback routine)。若發生錯誤,則可選擇是否提供第二次回呼。第三項參數為選項介面 (亦可選擇是否使用之),可設定位置回傳的的最長時間,與請求的等待時間。<br>
 若不論定位精確度而想儘快固定單一位置,則可使用 <code>getCurrentPosition()</code>。以具備 GPS 的裝置為例,往往需耗時 1 分鐘或更長的時間而固定 GPS 資訊。也因此,<code>getCurrentPosition()</code> 可能取得較低精確度的資料 (IP 位置或 WiFi) 而隨即開始作業。</p>

<div class="note">
<p><strong>注意:</strong>依預設值,<a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.getCurrentPosition" title="The Geolocation.getCurrentPosition() method is used to get the current position of the device."><code>getCurrentPosition()</code></a> 將儘快回傳較低精確度的結果。若不論精確度而只要儘快獲得答案,則可使用 <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.getCurrentPosition" title="The Geolocation.getCurrentPosition() method is used to get the current position of the device."><code>getCurrentPosition()</code></a>。舉例來說,搭載 GPS 的裝置可能需要一段時間才能取得 GPS 定位資訊,所以可能將低精確度的資料 (IP 位置或 Wifi) 回傳至 <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.getCurrentPosition" title="The Geolocation.getCurrentPosition() method is used to get the current position of the device."><code>getCurrentPosition()</code></a>。</p>
</div>

<pre class="brush: js">navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});</pre>

<p>一旦取得定位位置之後,上列範例隨即將執行 <code>do_something() </code>函式。</p>

<h3 id="觀看目前位置">觀看目前位置</h3>

<p>如果定位資料改變 (可能是裝置移動,或取得更精確的地理位置資訊),則可設定 1 組回呼函式,使其隨著更新過的定位資訊而呼叫之。而這個動作可透過 <code>watchPosition() 函式</code>完成。<a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.watchPosition" title="The Geolocation.watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function."><code>watchPosition()</code></a> 所具備的輸入參數與 <code>getCurrentPosition() </code>相同。回呼函式將呼叫數次,讓瀏覽器可於使用者移動期間更新位置,或可根據目前所使用的不同定位技術,提供更精確的定位資訊。若一直未回傳有效結果,則錯誤回呼 (Error Callback) 函式僅將呼叫 1 次。另請注意,錯誤回呼函式僅限於 <code>getCurrentPosition(),因此為選填</code>。</p>

<div class="note">
<p><strong>注意:</strong>不需啟動 <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.getCurrentPosition" title="The Geolocation.getCurrentPosition() method is used to get the current position of the device."><code>getCurrentPosition()</code></a> 呼叫,亦可使用 <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.watchPosition" title="The Geolocation.watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function."><code>watchPosition()</code></a>。</p>
</div>

<pre class="brush: js">var watchID = navigator.geolocation.watchPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
}
);</pre>

<p><code>watchPosition()</code> 函式將回傳 1 組 ID 編號,專用以識別必要的定位監看員 (Watcher)。而此數值若搭配 <code>clearWatch() </code>函式,即可停止觀看使用者的位置。</p>

<pre>navigator.geolocation.clearWatch(watchID);
</pre>

<h3 id="微調回應">微調回應</h3>

<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.getCurrentPosition" title="The Geolocation.getCurrentPosition() method is used to get the current position of the device."><code>getCurrentPosition()</code></a> 與 <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.watchPosition" title="The Geolocation.watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function."><code>watchPosition()</code></a> 均可容納 1 組成功回呼、1 組錯誤回呼 (選填)、1 組 <code>PositionOptions</code> 物件 (選填)。</p>

<p>對 <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.watchPosition" title="The Geolocation.watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function."><code>watchPosition</code></a> 的呼叫應類似如下:</p>

<pre class="brush: js">function geo_success(position) {
  do_something(position.coords.latitude, position.coords.longitude);
}

function geo_error() {
  alert("Sorry, no position available.");
}

var geo_options = {
  enableHighAccuracy: true,
  maximumAge        : 30000,
  timeout           : 27000
};

var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);</pre>

<p><a id="fck_paste_padding">現成的 watchPosition Demo:</a><a class="external" href="http://www.thedotproduct.org/experiments/geo/">http://www.thedotproduct.org/experiments/geo/</a><br>
 <a id="fck_paste_padding"></a></p>

<h2 id="敘述位置">敘述位置</h2>

<p>以 <code>Position</code> 物件參照 <code>Coordinates</code> 物件,即可敘述使用者的位置。</p>

<h2 id="處理錯誤">處理錯誤</h2>

<p>在呼叫 <code>getCurrentPosition()</code> 或 <code>watchPosition() 時,</code>若獲得錯誤回呼函式,則<code>錯誤回呼函式的第一組參數將為 PositionError 物件:</code></p>

<pre>function errorCallback(<code>error</code>) {  alert('ERROR(' +<code> error</code>.<code>code </code>+ '): ' +<code> error</code>.<code>message</code>);};
</pre>

<h2 id="地理位置定位實際範例">地理位置定位實際範例</h2>

<h3 id="HTML_內容">HTML 內容</h3>

<pre>&lt;p&gt;&lt;button onclick="geoFindMe()"&gt;<code>Show my location</code>&lt;/button&gt;&lt;/p&gt;
&lt;div id="out"&gt;&lt;/div&gt;</pre>

<h3 id="JavaScript_內容">JavaScript 內容</h3>

<pre class="brush: js;">function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "&lt;p&gt;Geolocation is not supported by your browser&lt;/p&gt;";
    return;
  }

  function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    output.innerHTML = '&lt;p&gt;Latitude is ' + latitude + '° &lt;br&gt;Longitude is ' + longitude + '°&lt;/p&gt;';

    var img = new Image();
    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&amp;zoom=13&amp;size=300x300&amp;sensor=false";

    output.appendChild(img);
  };

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  };

  output.innerHTML = "&lt;p&gt;Locating…&lt;/p&gt;";

  navigator.geolocation.getCurrentPosition(success, error);
}
</pre>

<h3 id="現場測試結果">現場測試結果</h3>

<p>若無法顯示,可至本文右上角「Language」切換回英文原文觀看。</p>


<p>{{EmbedLiveSample('Examples', 350, 150, "", "", "", "geolocation")}}</p>


<h2 id="請求權限">請求權限</h2>

<p>addons.mozilla.org 上所提供的任何附加元件,只要使用地理位置定位資料,均必須明確取得許可才能繼續作業。下列函式詢問許可的方法,則類似網頁詢問許可的自動提示方法,但更為簡單。若為可套用的狀態,則使用者的回應將儲存於 <code>pref</code> 參數所指定的偏好中。於 <code>callback</code> 參數中所提供的函式,將透過 1 組代表使用者反應的布林值而呼叫之。若使用者的回應為 <code>true</code>,則附加元件才會存取地理位置定位資料。</p>

<pre class="brush: js">function prompt(window, pref, message, callback) {
    let branch = Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(Components.interfaces.nsIPrefBranch);

    if (branch.getPrefType(pref) === branch.PREF_STRING) {
        switch (branch.getCharPref(pref)) {
        case "always":
            return callback(true);
        case "never":
            return callback(false);
        }
    }

    let done = false;

    function remember(value, result) {
        return function() {
            done = true;
            branch.setCharPref(pref, value);
            callback(result);
        }
    }

    let self = window.PopupNotifications.show(
        window.gBrowser.selectedBrowser,
        "geolocation",
        message,
        "geo-notification-icon",
        {
            label: "Share Location",
            accessKey: "S",
            callback: function(notification) {
                done = true;
                callback(true);
            }
        }, [
            {
                label: "Always Share",
                accessKey: "A",
                callback: remember("always", true)
            },
            {
                label: "Never Share",
                accessKey: "N",
                callback: remember("never", false)
            }
        ], {
            eventCallback: function(event) {
                if (event === "dismissed") {
                    if (!done) callback(false);
                    done = true;
                    window.PopupNotifications.remove(self);
                }
            },
            persistWhileVisible: true
        });
}

prompt(window,
       "extensions.foo-addon.allowGeolocation",
       "Foo Add-on wants to know your location.",
       function callback(allowed) { alert(allowed); });
</pre>

<h2 id="瀏覽器相容性">瀏覽器相容性</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th>瀏覽器</th>
   <th>基本支援</th>
   <th><a class="external" href="http://dev.w3.org/geo/api/spec-source-v2.html">Geolocation Level 2</a></th>
  </tr>
  <tr>
   <td>Internet Explorer</td>
   <td>IE9 RC</td>
   <td>---</td>
  </tr>
  <tr>
   <td>Firefox (Gecko)</td>
   <td><strong>3.5</strong> (1.9.1)</td>
   <td>---</td>
  </tr>
  <tr>
   <td>Opera</td>
   <td><strong>10.60</strong></td>
   <td>---</td>
  </tr>
  <tr>
   <td>Safari | Chrome | WebKit</td>
   <td>5 | 5 | 533</td>
   <td>---</td>
  </tr>
 </tbody>
</table>

<h2 id="Gecko_註記">Gecko 註記</h2>

<p>Firefox 可透過 Google 的定位服務 (Google Location Services,GLS),根據使用者的 WiFi 資訊而找出使用者的位置。與 Google 之間所交換的資料,包含 WiFi 存取點 (Access Point) 資料、Access token (類似 2 個禮拜的 cookie)、使用者的 IP 位址。若需更多資訊,可參閱 <a href="http://www.mozilla.com/en-US/legal/privacy/" title="http://www.mozilla.com/en-US/legal/privacy/">Mozilla 的隱私權政策</a>與 <a href="http://www.google.com/privacy-lsf.html" title="http://www.google.com/privacy-lsf.html">Google 的隱私權政策</a>。其內將詳述資料的使用方式。</p>

<p>Firefox 3.6 (Gecko 1.9.2) 新支援了 <a href="http://catb.org/gpsd/" title="http://catb.org/gpsd/">GPSD</a> (GPS daemon) 服務,適合 Linux 的地理位置定位。</p>

<h2 id="另請參閱">另請參閱</h2>

<ul>
 <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation" title="The documentation about this has not yet been written; please consider contributing!"><code>navigator.geolocation</code></a></li>
 <li><a href="http://www.w3.org/TR/geolocation-API/" title="http://www.w3.org/TR/geolocation-API/">w3.org 的 Geolocation API </a></li>
 <li><a href="https://developer.mozilla.org/en-US/demos/tag/tech:geolocation" title="en-US/demos/tag/tech:geolocation/">Geolocation API 相關 Demos</a></li>
</ul>