Cordova-accelometer

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

Cordova-加速度計

Accelerometerプラグインは、 device-motion とも呼ばれます。 デバイスの動きを3次元で追跡するために使用されます。

手順1-加速度計プラグインのインストール

*cordova-CLI* を使用してこのプラグインをインストールします。 *コマンドプロンプト*ウィンドウに次のコードを入力します。
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugindevice-motion

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

このステップでは、 indexl ファイルに2つのボタンを追加します。 1つは現在の加速度を取得するために使用され、もう1つは加速度の変化を監視します。

<button id = "getAcceleration">GET ACCELERATION</button>
<button id = "watchAcceleration">WATCH ACCELERATION</button>

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

ボタンのイベントリスナーを index.js 内の onDeviceReady 関数に追加しましょう。

document.getElementById("getAcceleration").addEventListener("click", getAcceleration);
document.getElementById("watchAcceleration").addEventListener(
   "click", watchAcceleration);

ステップ4-関数の作成

次に、2つの関数を作成します。 最初の関数は現在の加速度を取得するために使用され、2番目の関数は加速度を監視し、3秒ごとに加速度に関する情報がトリガーされます。 また、 setTimeout 関数でラップされた clearWatch 関数を追加して、指定された時間枠の後に加速の監視を停止します。 frequency パラメーターは、3秒ごとにコールバック関数をトリガーするために使用されます。

function getAcceleration() {
   navigator.accelerometer.getCurrentAcceleration(
      accelerometerSuccess, accelerometerError);

   function accelerometerSuccess(acceleration) {
      alert('Acceleration X: ' + acceleration.x + '\n' +
         'Acceleration Y: ' + acceleration.y + '\n' +
         'Acceleration Z: ' + acceleration.z + '\n' +
         'Timestamp: '      + acceleration.timestamp + '\n');
   };

   function accelerometerError() {
      alert('onError!');
   };
}

function watchAcceleration() {
   var accelerometerOptions = {
      frequency: 3000
   }
   var watchID = navigator.accelerometer.watchAcceleration(
      accelerometerSuccess, accelerometerError, accelerometerOptions);

   function accelerometerSuccess(acceleration) {
      alert('Acceleration X: ' + acceleration.x + '\n' +
         'Acceleration Y: ' + acceleration.y + '\n' +
         'Acceleration Z: ' + acceleration.z + '\n' +
         'Timestamp: '      + acceleration.timestamp + '\n');

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

   function accelerometerError() {
      alert('onError!');
   };

}
*GET ACCELERATION* ボタンを押すと、現在の加速度値が取得されます。 *WATCH ACCELERATION* ボタンを押すと、アラートが3秒ごとにトリガーされます。 3番目のアラートが表示された後、 *clearWatch* 関数が呼び出され、タイムアウトを10000ミリ秒に設定しているため、アラートはこれ以上表示されません。

Cordova Acceleration