Listen to DeviceOrientation events.
This example shows how to track changes in device orientation. gyronorm.js library is used to access and normalize the events from the browser.
<!DOCTYPE html>
<html>
<head>
<title>Device Orientation</title>
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://unpkg.com/gyronorm@2.0.6/dist/gyronorm.complete.min.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<p>
<div>α : <code id="alpha"></code></div>
<div>β : <code id="beta"></code></div>
<div>γ : <code id="gamma"></code></div>
</p>
<script>
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import {toRadians} from 'ol/math.js';
import OSM from 'ol/source/OSM.js';
var view = new View({
center: [0, 0],
zoom: 2
});
var map = new Map({
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: view
});
function el(id) {
return document.getElementById(id);
}
var gn = new GyroNorm();
gn.init().then(function() {
gn.start(function(event) {
var center = view.getCenter();
var resolution = view.getResolution();
var alpha = toRadians(event.do.beta);
var beta = toRadians(event.do.beta);
var gamma = toRadians(event.do.gamma);
el('alpha').innerText = alpha + ' [rad]';
el('beta').innerText = beta + ' [rad]';
el('gamma').innerText = gamma + ' [rad]';
center[0] -= resolution * gamma * 25;
center[1] += resolution * beta * 25;
view.setCenter(view.constrainCenter(center));
});
});
</script>
</body>
</html>