您是否想知道在使用JavaScript时是否可以在Safari中访问iPhone指南针?我看到了如何访问GPS,但我无法弄清楚指南针的访问方法。
您是否想知道在使用JavaScript时是否可以在Safari中访问iPhone指南针?我看到了如何访问GPS,但我无法弄清楚指南针的访问方法。
在iOS上,您可以像这样检索罗盘值。
window.addEventListener('deviceorientation', function(e) {
console.log( e.webkitCompassHeading );
}, false);
想要了解更多信息,请阅读苹果设备方向事件文档。
希望能对你有所帮助。
除非您使用类似 iPhoneGap 的工具,否则无法通过JavaScript访问该信息。
在此之前是这样的,在iOS 5中,您可以在JS中使用指南针方向。https://developer.apple.com/documentation/webkitjs/deviceorientationevent/1804777-webkitcompassheading
对于Android系统,它可以自动运行,而对于iOS系统,则需要点击启动它。以下是您可用的部分代码:
startBtn.addEventListener("click", startCompass);
function startCompass() {
if (isIOS) {
DeviceOrientationEvent.requestPermission()
.then((response) => {
if (response === "granted") {
window.addEventListener("deviceorientation", handler, true);
} else {
alert("has to be allowed!");
}
})
.catch(() => alert("not supported"));
} else {
window.addEventListener("deviceorientationabsolute", handler, true);
}
}
function handler(e) {
const degree = e.webkitCompassHeading || Math.abs(e.alpha - 360);
}
我建议您使用LeafletJS与此插件
https://github.com/stefanocudini/leaflet-compass
非常容易使用,具有事件和方法。
您可以在此处尝试演示:
https://opengeo.tech/maps/leaflet-compass/