Chrome 如何在JavaScript中返回罗盘航向?

qyzbxkaa  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(81)

我已经看了几个关于如何从Javascript返回罗盘航向的方法,并找到了一个通过navigator.geolocation.watchposition的方法。
有一个值应该返回一个罗盘航向(coords.heading),但它只返回null

navigator.geolocation.watchPosition((data) =>{
    console.log(data.coords.heading);
    lat = data.coords.latitude; //Lat and long values return correct coords
    long = data.coords.longitude;
    heading = data.coords.heading; //this value returns null
});

是这个方法过时了,还是我做错了什么?
我一直在通过安全连接在装有Chrome的Android设备上测试这一点。
(我看过以前关于这个的问题,但我只能找到2013年的问题,所以我想有些东西可能已经被弃用了。)

r6l8ljro

r6l8ljro1#

我把这个留在这里是因为我在同样的问题上浪费了一整天。你正在寻找错误的API来获取手机的方向。地理位置中的航向属性不是罗盘方向,而是基于电话的移动计算的方向。如果你站着不动,航向是空的。当你移动的时候,把航向指向你移动的方向.查看此文档:https://developer.mozilla.org/en-US/docs/Web/API/GeolocationCoordinates/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);
}

相关问题