Cordova-device-orientation

提供:Dev Guides
移動先:案内検索

Cordova-デバイスの向き

コンパスは、地理的な北の基点に対する方向を示すために使用されます。

手順1-デバイスの向きのプラグインをインストールする

  • コマンドプロンプト*ウィンドウを開き、次を実行します。
C:\Users\username\Desktop\CordovaProject>cordova plugin
   add cordova-plugindevice-orientation

ステップ2-ボタンを追加する

このプラグインは acceleration プラグインに似ています。 indexl に2つのボタンを作成します。

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

手順3-イベントリスナーの追加

次に、 index.jsonDeviceReady 関数内に*イベントリスナー*を追加します。

document.getElementById("getOrientation").addEventListener("click", getOrientation);
document.getElementById("watchOrientation").addEventListener("click", watchOrientation);

ステップ4-関数の作成

2つの関数を作成します。最初の関数は現在の加速度を生成し、もう1つの関数は方向の変化をチェックします。 frequency オプションを再び使用して、3秒ごとに発生する変更を監視していることがわかります。

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

コンパスプラグインは加速プラグインとほとんど同じなので、今回はエラーコードを表示します。 一部のデバイスには、コンパスが機能するために必要な磁気センサーがありません。 デバイスにそれがない場合、次のエラーが表示されます。

Cordova Compass Error