@capacitor/motion
The Motion API tracks accelerometer and device orientation (compass heading, etc.)
Install
npm install @capacitor/motion
npx cap sync
Permissions
This plugin is currently implemented using Web APIs. On iOS devices, permission must be requested before accessing device motion or orientation events. To request permission, prompt the user on any user-initiated action (such as a button click):
import { PluginListenerHandle } from '@capacitor/core';
import { Motion } from '@capacitor/motion';
let accelHandler: PluginListenerHandle;
let orientationHandler: PluginListenerHandle;
myAccelerationButton.addEventListener('click', async () => {
if (typeof DeviceMotionEvent.requestPermission === 'function') {
try {
const permission = await DeviceMotionEvent.requestPermission();
if (permission !== 'granted') return;
} catch (e) {
// Handle error
return;
}
}
// Once the user approves, can start listening:
accelHandler = await Motion.addListener('accel', event => {
console.log('Device motion event:', event);
});
});
myOrientationButton.addEventListener('click', async () => {
if (typeof DeviceOrientationEvent.requestPermission === 'function') {
try {
const permission = await DeviceOrientationEvent.requestPermission();
if (permission !== 'granted') return;
} catch (e) {
// Handle error
return;
}
}
// Once the user approves, can start listening:
orientationHandler = await Motion.addListener('orientation', event => {
console.log('Device orientation event:', event);
});
});
// Stop the acceleration listener
const stopAcceleration = () => {
if (accelHandler) {
accelHandler.remove();
}
};
// Stop the orientation listener
const stopOrientation = () => {
if (orientationHandler) {
orientationHandler.remove();
}
};
// Remove all listeners
const removeListeners = () => {
Motion.removeAllListeners();
};
See the
DeviceMotionEvent
and
DeviceOrientationEvent
APIs to understand the data supplied in the 'accel' and 'orientation'
events respectively.
API
addListener('accel', ...)
addListener(eventName: 'accel', listenerFunc: AccelListener) => Promise<PluginListenerHandle>
Add a listener for accelerometer data
| Param | Type |
|---|---|
eventName | 'accel' |
listenerFunc | |
Returns:
Promise<PluginListenerHandle>
Since: 1.0.0