如何通过此传感器API使用磁力计?

时间:2018-10-11 10:35:40

标签: android google-chrome magnetometer

我正在尝试使用此Sensor API中的磁力计,但不确定是否正确使用了

我将示例代码从their site复制并编辑到了我的测试站点中;

let sensor = new Magnetometer();
sensor.start();

sensor.onreading = () => {
    console.log("Magnetic field along the X-axis " + sensor.x);
    console.log("Magnetic field along the Y-axis " + sensor.y);
    console.log("Magnetic field along the Z-axis " + sensor.z);

    document.getElementById("x").innerHTML = "X = " + sensor.x;
    document.getElementById("y").innerHTML = "Y = " + sensor.y;
    document.getElementById("z").innerHTML = "Z = " + sensor.z;
};

sensor.onerror = event => console.log(event.error.name, event.error.message);

但是,当我加载页面时,它没有任何读数。在笔记本电脑上检查该网站会返回此错误消息;

Uncaught ReferenceError: Magnetometer is not defined
    at magnetometer.js:1

对此有任何见识将不胜感激。

1 个答案:

答案 0 :(得分:0)

我找到了答案。环顾四周后,我发现您需要转到chrome://flags/#enable-generic-sensor-extra-classes并启用Generic Sensor Extra Classes

我不确定为什么会这样,但是我现在正在得到我想要的读数。