Saturday, 4 June 2016

Post 52: detect device motion with Ionic

In this post I'll show you how to detect the motion of your device with Ionic framework.

First create an Ionic project and then add a platform. How to do this with android is explained here.

I created a "tabs" ionic project. But you can choose whatever project type ("blank", "sidemenu") you want.
Download the ng-cordova zip file here. After downloading unzip and find the file "ng-cordova.min.js". The file is located at "ng-cordova-master\dist\". Put that file into the following folder of our project: "yourProject\www\js\".


Add this line in your index.html
 
1
2
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>

Install the following two plugins:

1
2
cordova plugin add cordova-plugin-device-motion
cordova plugin add cordova-plugin-whitelist

In your app.js add "ngCordova" to your service array:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova'])

Add this to your index.html:
    <ion-pane ng-controller="MotionController">
        <ion-header-bar class="bar-stable">
            <h1 class="title">Start Watching Device Motion</h1>
        </ion-header-bar>

        <ion-content>
            <div class="list">
                <label class="item item-input">
                    <span class="input-label">Frequency</span>
                    <input type="text" placeholder="0" ng-model="options.frequency">
                </label>
            </div>
            <button class="button button-full button-positive" ng-click="startWatching()">
                Start Measurement
            </button>
            <button class="button button-full button-positive" ng-click="stopWatching()">
                Stop Measurement
            </button>
            <h2>X: {{measurements.x}}</h2>
            <h2>Y: {{measurements.y}}</h2>
            <h2>Z: {{measurements.z}}</h2>
        </ion-content>
    </ion-pane>


And add this into the header of your index.html

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

In your controller.js add the MotionController:
.controller('MotionController', function($scope, $cordovaDeviceMotion, $ionicPlatform) {
 
// watch Acceleration options $scope.options = { frequency: 100, // Measure every 100ms deviation : 25 // We'll use deviation to determine the shake event, best values in the range between 25 and 30 }; // Current measurements $scope.measurements = { x : null, y : null, z : null, timestamp : null } // Previous measurements $scope.previousMeasurements = { x : null, y : null, z : null, timestamp : null } // Watcher object $scope.watch = null; // Start measurements when Cordova device is ready $ionicPlatform.ready(function() { //Start Watching method $scope.startWatching = function() { // Device motion configuration $scope.watch = $cordovaDeviceMotion.watchAcceleration($scope.options); // Device motion initilaization $scope.watch.then(null, function(error) { console.log('Error'); },function(result) { // Set current data $scope.measurements.x = result.x; $scope.measurements.y = result.y; $scope.measurements.z = result.z; $scope.measurements.timestamp = result.timestamp; // Detecta shake $scope.detectShake(result); }); }; // Stop watching method $scope.stopWatching = function() { $scope.watch.clearWatch(); } // Detect shake method $scope.detectShake = function(result) { //Object to hold measurement difference between current and old data var measurementsChange = {}; // Calculate measurement change only if we have two sets of data, current and old if ($scope.previousMeasurements.x !== null) { measurementsChange.x = Math.abs($scope.previousMeasurements.x, result.x); measurementsChange.y = Math.abs($scope.previousMeasurements.y, result.y); measurementsChange.z = Math.abs($scope.previousMeasurements.z, result.z); } // If measurement change is bigger then predefined deviation if (measurementsChange.x + measurementsChange.y + measurementsChange.z > $scope.options.deviation) { $scope.stopWatching(); // Stop watching because it will start triggering like hell console.log('Shake detected'); // shake detected setTimeout($scope.startWatching(), 1000); // Again start watching after 1 sex // Clean previous measurements after succesfull shake detection, so we can do it next time $scope.previousMeasurements = { x: null, y: null, z: null } } else { // On first measurements set it as the previous one $scope.previousMeasurements = { x: result.x, y: result.y, z: result.z } } } }); $scope.$on('$ionicView.beforeLeave', function(){ $scope.watch.clearWatch(); // Turn off motion detection watcher });
});



Source:
http://www.gajotres.net/detecting-device-motion-with-ionic-framework-and-ngcordova/

Tuesday, 31 May 2016

Post 51: MVG (Münchener Verkehrsgesellschaft) U-Bahn as a CSS art with one DIV element

This train is called MVG U-Bahn. It's operating in Munich. I drew it with CSS and one HTML element.




Monday, 16 May 2016

Post 50: Solutions to "Introduction to Algorithms 3rd edition" by CLRS

Starting with today I'll post my solution to the book "Introduction to Algorithms 3rd Edition" by CLRS on this blog:

http://solution-clrs.blogspot.de/

Every post that I make there, contains a solution for one excercise. If you think I made a mistake feel free to comment on the corresponding post.

Sunday, 8 May 2016

Post 48: Source for finding angularJS libraries

If you want to download angularJS library on your local machine, e.g. so you can also work offline, then you got these options:

- Go to this page:

https://cdnjs.com/libraries/angular.js/

Then select the angularJS version and after that find the library.

- Or go to https://docs.angularjs.org/api

Then search for the module.

Saturday, 7 May 2016

Post 47: AngularJS directives

You can define directives in AngularJS as
- Element ("E"):
<my-directive></my-directive>
notice that we don't use self closing tags, i.e. <my-directive/> because some browsers can't handle self-closing tags

Use this for UI widgets.

- Attribute ("A"):
<h3 my-directive></h3>

Use this for mixin behaviours, e.g. tooltip

- Class name ("C")

<h3 class="my-directive"></h3>

- Comment ("M")
  <!-- directive: my-directive -->

Post 46: displaying a html module with ng-include

If you are writing AngularJS and want to use ng-include in order to display a html module within your page, for example this:

my-html-file.html:
<html ng-app="myAngularJSapp">
...
            <h3 ng-include="'product-title.html'"></h3>
...
</html>

my-module.html:
            <h1>{{product.name}}</h1>
            <h2>{{product.price | currency}}</h2>


Then you may notice this error message if you are loading your page with your file server:

angular.min.js:103 XMLHttpRequest cannot load file:///home/my-html-file.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.(anonymous function) @ angular.min.js:103
The reason why this happens is, that ng-include makes a XMLHttpRequest. If you're opening your page via your file server this XMLHttpRequest will not work because your localhost is not able to handle HTTP request.

Solution:
- run the code on a webserver
- Run a simple server with python -m SimpleHTTPServer
- install a simple server on your machine, e.g. https://github.com/devpaul/grunt-devserver 

Tweet