Magnetometer
Sensor API
Sensor API
The **`Magnetometer`** interface of the [Sensor APIs](/docs/Web/API/Sensor_APIs) provides information about the magnetic field as detected by the device's primary magnetometer sensor.
To use this sensor, the user must grant permission to the `'magnetometer'` device sensor through the [Permissions API](/docs/Web/API/Permissions_API). In addition, this feature may be blocked by a [Permissions Policy](/docs/Web/HTTP/Guides/Permissions_Policy) set on your server.
## Constructor
- Magnetometer()
- : Creates a new `Magnetometer` object.
## Instance properties
- Magnetometer.x
- : Returns a double containing the magnetic field around the device's x axis.
- Magnetometer.y
- : Returns a double containing the magnetic field around the device's y axis.
- Magnetometer.z
- : Returns a double containing the magnetic field around the device's z axis.
## Instance methods
_`Magnetometer` doesn't have own methods. However, it inherits methods from its parent interfaces, Sensor and EventTarget._
## Events
_`Magnetometer` doesn't have own events. However, it inherits events from its parent interface, Sensor._
## Example
The magnetometer is typically read in the reading event callback. In the example below this occurs sixty times a second.
```js
let magSensor = new Magnetometer({ frequency: 60 });
magSensor.addEventListener("reading", (e) => {
console.log(`Magnetic field along the X-axis ${magSensor.x}`);
console.log(`Magnetic field along the Y-axis ${magSensor.y}`);
console.log(`Magnetic field along the Z-axis ${magSensor.z}`);
});
magSensor.start();
```
## Specifications
## Browser compatibility
Cite this
"Magnetometer". MDN Web Docs. CC BY-SA 2.5 (MDN). https://developer.mozilla.org/en-US/docs/Web/API/Magnetometer JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy