磁北定位

问题描述 投票:0回答:1

我正在制作一个指向静态坐标位置(纬度,经度)的交互式指南针。我通过以下方式读取用户的位置:

navigator.geolocation.watchPosition( positionFound , error );

我旋转指南针:

heading = Math.atan2( Math.sin(locationLon-userLon) * Math.cos(locationLat), Math.cos(userLat) * Math.sin(locationLat) - Math.sin(userLat) * Math.cos(locationLat) * Math.cos(locationLon-userLon));
heading = heading * 180/Math.PI + 180;

现在的问题是每个用户都会获得另一个指向位置,但它必须指向相同的位置,因为他们使用相同的坐标。

Click to get a picture of the compass page

现在我发现,当页面加载或刷新时,北总是停留在移动设备的第一个前面(北)位置。而不是真正的北方。 那么有没有办法始终获得真正的北位置(磁北)?

这是一个简短的演示:https://mister-e.nl/compass (在手机上测试一下,有时转动手机刷新一下)

这是我的第一个主题(初学者)。我希望我已经为你们解释清楚了。你也许可以帮助我解决这个问题。如果您需要查看更多代码,请告诉我。

javascript math geolocation coordinates compass-geolocation
1个回答
0
投票

我把这个留在这里是因为我浪费了一整天的时间来解决同样的问题。 您正在寻找错误的 API 来获取手机的方向。地理位置中的航向属性不是指南针方向,而是根据手机的移动计算出的方向。所以如果你站着不动,标题就是空的。一旦您移动,航向就会指向您的移动方向。请参阅此文档:https://developer.mozilla.org/en-US/docs/Web/API/GeolocationCooperatives/heading

您正在寻找的是“deviceorientation”事件。对于 iOS/Safari,您必须首先手动请求该功能。 (这是 Typescript 代码)

const isIOS = !(
    navigator.userAgent.match(/(iPod|iPhone|iPad)/) &&
    navigator.userAgent.match(/AppleWebKit/)
);
if (isIOS) {
    (DeviceOrientationEvent as any).requestPermission()
        .then((response: any) => {
            if (response === "granted") {
                window.addEventListener("deviceorientation", this.receivedNewHeading, true);
            } else {
                alert("has to be allowed!");
            }
        })
        .catch(() => alert("not supported"));
} else {
    window.addEventListener("deviceorientationabsolute", this.receivedNewHeading, true);
}

© www.soinside.com 2019 - 2024. All rights reserved.