Cordova裝置方向


指南針是用來顯示相對於地理北極的基本點的方向。

第1步 - 安裝裝置的方向外掛

開啟命令提示字元視窗,並執行以下命令。
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-orientation

第2步 - 新增按鈕

如果你有學習我們前面教學,你可能會注意到,這個外掛它類似於加速度外掛。我們在本教學中使用的是同一個概念。讓我們在 index.html 檔案中建立兩個按鈕

<button id = "getOrientation">GET ORIENTATION</button>
<button id = "watchOrientation">WATCH ORIENTATION</button>

第3步 - 新增事件監聽器

現在,我們將在index.js中的 onDeviceReady函式內部新增事件偵聽器。
document.getElementById("getOrientation").addEventListener("click", getOrientation);
document.getElementById("watchOrientation").addEventListener("click", watchOrientation);

第4步 - 建立函式

我們將建立兩個函式,一個來獲取當前加速度,另外一個用來監視方向的變化。可以看到再次使用頻率選項,因為我們希望每三秒鐘觀察其變化。

function getOrientation(){
   navigator.compass.getCurrentHeading(compassSuccess, compassError);

   function compassSuccess(heading) {
      alert('Heading: ' + heading.magneticHeading);
   };

   function compassError(error) {
      alert('CompassError: ' + error.code);
   };
	
}

function watchOrientation(){
    
   var compassOptions = {
      frequency: 3000
   }

   var watchID = navigator.compass.watchHeading(compassSuccess, compassError, compassOptions);

   function compassSuccess(heading) {
      alert('Heading: ' + heading.magneticHeading);

      setTimeout(function() {
         navigator.compass.clearWatch(watchID);
      }, 10000);

   };

   function compassError(error) {
      alert('CompassError: ' + error.code);
   };
	
} 

由於指南針外掛幾乎與加速度外掛是一樣的,這次我們告訴你錯誤程式碼。一些裝置不具有指南針工作所需要的磁感測器。如果您的裝置沒有,會得到下面的錯誤。