Cordova - 地理位置



地理位置用於獲取裝置的經緯度資訊。

步驟 1 - 安裝外掛

我們可以透過在命令提示符視窗中鍵入以下程式碼來安裝此外掛。

C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-geolocation

步驟 2 - 新增按鈕

在本教程中,我們將向您展示如何獲取當前位置以及如何監視位置變化。我們首先需要建立將呼叫這些函式的按鈕。

<button id = "getPosition">CURRENT POSITION</button>
<button id = "watchPosition">WATCH POSITION</button>

步驟 3 - 新增事件監聽器

現在,我們想要在裝置準備好時新增事件監聽器。我們將把下面的程式碼示例新增到index.js中的onDeviceReady函式中。

document.getElementById("getPosition").addEventListener("click", getPosition);
document.getElementById("watchPosition").addEventListener("click", watchPosition);	

步驟 3 - 建立函式

必須為兩個事件監聽器建立兩個函式。一個用於獲取當前位置,另一個用於監視位置。

function getPosition() {
   var options = {
      enableHighAccuracy: true,
      maximumAge: 3600000
   }
   var watchID = navigator.geolocation.getCurrentPosition(onSuccess, onError, options);

   function onSuccess(position) {
      alert('Latitude: '          + position.coords.latitude          + '\n' +
         'Longitude: '         + position.coords.longitude         + '\n' +
         'Altitude: '          + position.coords.altitude          + '\n' +
         'Accuracy: '          + position.coords.accuracy          + '\n' +
         'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
         'Heading: '           + position.coords.heading           + '\n' +
         'Speed: '             + position.coords.speed             + '\n' +
         'Timestamp: '         + position.timestamp                + '\n');
   };

   function onError(error) {
      alert('code: '    + error.code    + '\n' + 'message: ' + error.message + '\n');
   }
}

function watchPosition() {
   var options = {
      maximumAge: 3600000,
      timeout: 3000,
      enableHighAccuracy: true,
   }
   var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);

   function onSuccess(position) {
      alert('Latitude: '          + position.coords.latitude          + '\n' +
         'Longitude: '         + position.coords.longitude         + '\n' +
         'Altitude: '          + position.coords.altitude          + '\n' +
         'Accuracy: '          + position.coords.accuracy          + '\n' +
         'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
         'Heading: '           + position.coords.heading           + '\n' +
         'Speed: '             + position.coords.speed             + '\n' +
         'Timestamp: '         + position.timestamp                + '\n');
   };

   function onError(error) {
      alert('code: '    + error.code    + '\n' +'message: ' + error.message + '\n');
   }
}

在上面的示例中,我們使用了兩種方法 - getCurrentPositionwatchPosition。這兩個函式都使用三個引數。單擊當前位置按鈕後,警報將顯示地理位置值。

Cordova Geolocation

如果我們點選監視位置按鈕,則每三秒鐘就會觸發相同的警報。這樣我們就可以跟蹤使用者裝置的移動變化。

注意

此外掛使用 GPS。有時它無法及時返回值,請求將返回超時錯誤。這就是為什麼我們指定了enableHighAccuracy: truemaximumAge: 3600000。這意味著如果請求沒有及時完成,我們將使用最後一個已知值。在我們的示例中,我們將maximumAge設定為 3600000 毫秒。

廣告