我正在使用以下代码在mapbox的webview中检测设备的旋转。我必须随着设备的旋转一起旋转地图。它基本上可以正常工作,但是只有一个问题。
当我们停下手时,角度/方位角/航向(alpha)值也会在停止之前持续一段时间,因此,地图也持续旋转了很长时间,当角度/轴承停止更换。
是否有任何方法可以使角度值在设备旋转停止后立即停止变化,从而停止地图旋转?
Js
$(document).ready(function(){
showmap();
});
window.addEventListener("deviceorientationabsolute", manageCompass, true);
var alpha;
function manageCompass(event) {
if (event.webkitCompassHeading) {
absoluteHeading = event.webkitCompassHeading + 180;
} else {
absoluteHeading = 180 - event.alpha;
}
console.log(absoluteHeading);
alpha = absoluteHeading;
document.getElementById("info").innerHTML = JSON.stringify(parseInt(alpha));
if(map != undefined){
map.rotateTo(alpha,{duration:1});
}
}
function showmap(){
map = new mapboxgl.Map({
style: 'mapbox://styles/mash12/ck9jmdjxz0r4p1irzk8xfteyv',
center: [77.052024, 28.459822]
pitch: 95,
bearing: 0,
container: 'map',
antialias: false,
});
map.on('load', function() {
// Insert the layer beneath any symbol layer.
console.log("map loaded");
var layers = map.getStyle().layers;
var labelLayerId;
for (var i = 0; i < layers.length; i++) {
if (layers[i].type === 'symbol' && layers[i].layout['text-field']) {
labelLayerId = layers[i].id;
break;
}
}
});
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Locate the user</title>
<!-- <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />-->
<meta name="viewport" content="width=device-width,
user-scalable=no, initial-scale=1, maximum-scale=1, user-scalable=0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link rel="stylesheet" href="css/main.css">
<link href="https://api.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.js"></script>
</head>
<body>
<div id="map"></div>
<pre id="info"></pre>
<script src="js/main.js"></script>
</body>
</html>
Css:
body { margin: 0; padding: 0;}
#map { position: absolute; top: 0; bottom: 0; width: 100%;}
#info {
display: block;
position: relative;
margin: 0px auto;
width: 50%;
padding: 10px;
border: none;
border-radius: 3px;
font-size: 12px;
text-align: center;
color: #222;
opacity: 1;
/*background: #fff;*/
}