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 lang="en">
<head>
<title>Device Orientation</title>
<!-- 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>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</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 src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import {toRadians} from 'ol/math';
import OSM from 'ol/source/OSM';
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.alpha);
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(center);
});
});
{
"name": "device-orientation",
"dependencies": {
"ol": "6.1.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}