Page Example

Spirit Level Sample Overview

The Spirit Level sample application demonstrates how you can use the W3C devicemotion event in your application to monitor the inclination of the device.

The following figure illustrates the main screen of the Spirit Level.

Figure: Spirit Level screen

Spirit Level screen

The application opens with the main screen that represents the inclination of the device.

Source Files

You can create and view the sample application project including the source files in the IDE.

File name Description
config.xml This file contains the application information for the platform to install and launch the application, including the view mode and the icon to be used in the device menu.
index.html This is a starting file from which the application starts loading. It contains the layout of the application screens.
js/app.js This file contains the code for handling the device orientation functionality of the application.

Implementation

To manage the motion events:

  1. Add the DeviceMotionEvent event listener:

    if (window.DeviceMotionEvent) 
    {
       window.addEventListener("devicemotion", onOrientationChange);
    } 
    else 
    {
       return false;
    }
    
  2. In the event callback, move the ball position by calculating the device inclination:

    noGravitation = dataEvent.acceleration;
    dataEvent = dataEvent.accelerationIncludingGravity;
    
    xDiff = dataEvent.x - noGravitation.x;
    if (Math.abs(xDiff) > MAX_G) 
    {
       xDiff = xDiff / Math.abs(xDiff) * MAX_G;
    }
    yDiff = -1 * (dataEvent.y - noGravitation.y);
    if (Math.abs(yDiff) > MAX_G) 
    {
       yDiff = yDiff / Math.abs(yDiff) * MAX_G;
    }
    
    xPos = (outerRadius - ballRadius) * xDiff / MAX_G;
    yPos = (outerRadius - ballRadius) * yDiff / MAX_G;
    
    ball.style.left = centerX - ballRadius + xPos + "px";
    ball.style.top = centerY - ballRadius + yPos + "px";
    
  3. Make the ball glow when it is in the inner circle (the device keeps in equilibration):

    if (inCircleRange(xPos, yPos, innerRadius - ballRadius)) 
    {
       if (statusGlow === false) 
       {
          setGlow(true);
       }
    } 
    else 
    {
       if (statusGlow === true) 
       {
          setGlow(false);
       }
    }
    
    function inCircleRange(x, y, r) 
    {
       return (x * x + y * y <= r * r) ? true : false;
    }