我使用here和here中的代码来确定通过相机查看手机的方向。
初始化后,代码看起来非常流畅和一致。问题是,当我加载代码时,无论我的设备指向哪个方向,它都变为90度(实际为89.7)。这是一个显而易见的问题,因为现在我不能简单地说dir < 45 && dir > 315 = "south"
。
这是由于我的特定硬件/软件吗? (Pixel XL,Chrome移动版)或我在代码中做错了什么?
更新:我遇到与this one from ArcGIS和this Marine Compass demo等复杂指南针相同的行为。
以下是完整代码:
function compassHeading(alpha, beta, gamma) {
// Convert degrees to radians
var alphaRad = alpha * (Math.PI / 180);
var betaRad = beta * (Math.PI / 180);
var gammaRad = gamma * (Math.PI / 180);
// Calculate equation components
var cA = Math.cos(alphaRad);
var sA = Math.sin(alphaRad);
var cB = Math.cos(betaRad);
var sB = Math.sin(betaRad);
var cG = Math.cos(gammaRad);
var sG = Math.sin(gammaRad);
// Calculate A, B, C rotation components
var rA = - cA * sG - sA * sB * cG;
var rB = - sA * sG + cA * sB * cG;
var rC = - cB * cG;
// Calculate compass heading
var compassHeading = Math.atan(rA / rB);
// Convert from half unit circle to whole unit circle
if(rB < 0) {
compassHeading += Math.PI;
}else if(rA < 0) {
compassHeading += 2 * Math.PI;
}
// Convert radians to degrees
compassHeading *= 180 / Math.PI;
return compassHeading;
}
document.addEventListener("DOMContentLoaded", function(event) {
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', function(eventData) {
let tiltLR = eventData.gamma;
let tiltFB = eventData.beta;
let dir = eventData.alpha;
deviceOrientationHandler(tiltLR, tiltFB, dir);
}, false);
}
function deviceOrientationHandler(tiltLR, tiltFB, dir) {
document.getElementById("tiltLR").innerHTML = 'tiltLR: ' + Math.ceil(tiltLR);
document.getElementById("tiltFB").innerHTML = 'tiltFB: ' + Math.ceil(tiltFB);
let heading = compassHeading(dir, tiltFB, tiltLR);
if (heading >= 0 && heading < 90) {
document.getElementById("direction").innerHTML = 'direction: S (' + heading + ')';
} else if (heading >= 90 && heading < 180) {
document.getElementById("direction").innerHTML = 'direction: W (' + heading + ')';
} else if (heading >= 180 && heading < 270) {
document.getElementById("direction").innerHTML = 'direction: N (' + heading + ')';
} else if (heading >= 270 && heading <= 360) {
document.getElementById("direction").innerHTML = 'direction: E (' + heading + ')';
} else {
document.getElementById("direction").innerHTML = 'direction: ? (' + heading + ')';
}
}
});