I’m trying to make a project to run on my phone that needs to detect my device’s motion, preferably without internet connection, I don’t think there’s a way to do this in snap without using javascript. I don’t know javascript, and have tried seaching online and asking ai, but I can’t get something that works. Ideally the javascript should return the device’s speed (like a speedometer) when being run in a call block.
Some things I’ve tried (javascript):
this one always gives an error. from ai:
function getDeviceSpeed() {
// Check if the browser supports DeviceMotion API
if (window.DeviceMotion) {
// Get initial parameters from the device
const options = {
frequency: 60,
sensitivity: 10
};
// Create a new instance of DeviceMotion API
const motion = new DeviceMotion(options);
return new Promise((resolve, reject) => {
// Start watching the device motion
motion.start();
// Watch the device motion every second
setInterval(() => {
motion.read().then((data) => {
// Resolve with the device's acceleration
resolve(data.acceleration);
}).catch((error) => {
// Reject if there is an error
reject(error);
});
}, 1000); // 1 second = 1000 milliseconds
});
} else {
throw new Error(‘DeviceMotion API not supported by the browser.’);
}
}
getDeviceSpeed().then((speed) => {
console.log(`The device's speed is ${speed}`);
}).catch((error) => {
console.error(error);
});
This one just does nothing; no error, and no output. From either ai or internet i dont remember:
function getDeviceMotion() {
// Check if the DeviceMotionEvent is supported
if (window.DeviceMotionEvent) {
// Define the callback function to handle motion data
function handleMotionEvent(event) {
// Extract acceleration data including gravity (in m/s²)
const acceleration = {
x: event.accelerationIncludingGravity.x,
y: event.accelerationIncludingGravity.y,
z: event.accelerationIncludingGravity.z
};
// Extract rotation rate (in degrees per second)
const rotationRate = {
alpha: event.rotationRate.alpha,
beta: event.rotationRate.beta,
gamma: event.rotationRate.gamma
};
// Extract the interval between data updates (in milliseconds)
const interval = event.interval;
// Return the collected motion data
return {
acceleration,
rotationRate,
interval
};
}
// Add the event listener to capture motion data
window.addEventListener("devicemotion", handleMotionEvent, true);
// Return a function to stop listening for motion events
return function stop() {
window.removeEventListener("devicemotion", handleMotionEvent, true);
};
} else {
console.error(“DeviceMotionEvent is not supported by this browser.”);
return null;
}
}
// Example usage:
// const stopListening = getDeviceMotion();
// To stop listening later, call: stopListening();