设备方向
设备方向示例。 设备 方向 gyronorm
TIP
使用微信打开预览链接并旋转手机。
本示例演示如何跟踪设备方向的变化。使用了 gyronorm.js 库来访问并规范化来自浏览器的事件。
main.js
js
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';
const view = new View({
center: [0, 0],
zoom: 2,
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: 'map',
view: view,
});
function el(id) {
return document.getElementById(id);
}
const gn = new GyroNorm();
gn.init().then(
function () {
gn.start(function (event) {
const center = view.getCenter();
const resolution = view.getResolution();
const alpha = toRadians(event.do.alpha);
const beta = toRadians(event.do.beta);
const 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);
});
},
function (e) {
el('unsupported').innerText =
typeof e === 'string' ? e : 'Could not initialize sensors';
},
);index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>设备方向</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<p>
<div id="unsupported" style="background-color: lightcoral; text-align: center;"></div>
<div>α : <code id="alpha"></code></div>
<div>β : <code id="beta"></code></div>
<div>γ : <code id="gamma"></code></div>
</p>
<script src="https://cdn.jsdelivr.net/npm/gyronorm@2.0.6/dist/gyronorm.complete.min.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "device-orientation",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}