Ionic/Cordova : Device Motion Plugin

Ionic is a complete open-source SDK for hybrid mobile app development. Built on top of AngularJS and Apache Cordova, Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass.

ngCordova was built to help make app development faster and more efficient than ever before. It gives you simple AngularJS wrappers for the most popular Cordova and PhoneGap plugins available, where you can take a picture, scan a barcode, upload a file, turn on your flashlight, get your current location, and much more with just a few lines of code.

ionic-cordova-device-motion-plugin

Device Motion($cordovaDeviceMotion) plugin provides access to the device’s accelerometer. The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation, in three dimensions along the x, y, and z axis. Here is the controller snippet below to find your device orientation. This code is well explained on the ngCordova official website. Here, I practically executed the code and uploaded on GitHub. I also executed the code on android platform, so that you can find the APK file include on it.

Controller:

angular.module('app.controllers', [])

.controller('MotionCtrl', function($ionicPlatform, $scope, $timeout, $cordovaDeviceMotion) {
    $ionicPlatform.ready(function() {
        // Values @ this instance
        $cordovaDeviceMotion.getCurrentAcceleration().then(function(result) {
            $scope.X = result.x;
            $scope.Y = result.y;
            $scope.Z = result.z;
            $scope.timeStamp = result.timestamp;
        }, function(err) {
            // An error occurred. Show a message to the user
            console.log(err);
        });
        // Keep watching for change in values
        // watch Acceleration
        var options = {
            frequency: 2000
        };
        $scope.watch = $cordovaDeviceMotion.watchAcceleration(options);
        $scope.watch.then(
            null,
            function(error) {
                // An error occurred
            },
            function(result) {
                $scope.X = result.x;
                $scope.Y = result.y;
                $scope.Z = result.z;
                $scope.timeStamp = result.timestamp;
            });
    });
})

Download via GitHub:

Download

Thank You !!
Please leave your valuable comments/suggestions/feedback on below comment box if any.

Leave a Reply

Your email address will not be published. Required fields are marked *