@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. Most browsers require permission before using this API. To request permission, prompt the user for permission on any user-initiated action (such as a button click):
import { PluginListenerHandle } from '@capacitor/core';
import { Motion } from '@capacitor/motion';
let accelHandler: PluginListenerHandle;
myButton.addEventListener('click', async () => {
try {
await DeviceMotionEvent.requestPermission();
} catch (e) {
// Handle error
return;
}
// Once the user approves, can start listening:
accelHandler = await Motion.addListener('accel', event => {
console.log('Device motion event:', event);
});
});
// Stop the acceleration listener
const stopAcceleration = () => {
if (accelHandler) {
accelHandler.remove();
}
};
// Remove all listeners
const removeListeners = () => {
Motion.removeAllListeners();
};
See the
DeviceMotionEvent
API to understand the data supplied in the 'accel' event.
API
addListener('accel', ...)
addListener(eventName: 'accel', listenerFunc: AccelListener) => Promise<PluginListenerHandle> & PluginListenerHandle
Add a listener for accelerometer data
Param | Type |
---|---|
eventName | 'accel' |
listenerFunc | AccelListener |
Returns: Promise<PluginListenerHandle> & PluginListenerHandle
Since: 1.0.0