W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
指南針用于顯示相對于地理北基點的方向。
打開命令提示符窗口并運行以下命令。
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-orientation
如果你按照我們的最后一個教程,你可能會注意到這個插件類似于加速插件。在本教程中,我們將遵循相同的概念。讓我們在 index.html 中創(chuàng)建兩個按鈕。
<button id = "getOrientation">GET ORIENTATION</button> <button id = "watchOrientation">WATCH ORIENTATION</button>
現(xiàn)在我們將在 index.js 中的 onDeviceReady 函數(shù)中添加事件監(jiān)聽器。
document.getElementById("getOrientation").addEventListener("click", getOrientation); document.getElementById("watchOrientation").addEventListener("click", watchOrientation);
我們將創(chuàng)建兩個函數(shù),一個獲取當前加速度,另一個查看方向更改。您可以看到我們正在使用頻率選項,因為我們想要每隔三秒觀察一次更改。
function getOrientation(){ navigator.compass.getCurrentHeading(compassSuccess, compassError); function compassSuccess(heading) { alert('Heading: ' + heading.magneticHeading); }; function compassError(error) { alert('CompassError: ' + error.code); }; } function watchOrientation(){ var compassOptions = { frequency: 3000 } var watchID = navigator.compass.watchHeading(compassSuccess, compassError, compassOptions); function compassSuccess(heading) { alert('Heading: ' + heading.magneticHeading); setTimeout(function() { navigator.compass.clearWatch(watchID); }, 10000); }; function compassError(error) { alert('CompassError: ' + error.code); }; }
由于指南針插件幾乎與加速插件相同,我們將在此時顯示錯誤代碼。 某些設備沒有磁羅盤工作所需的磁性傳感器。 如果您的設備沒有它,您會得到以下錯誤。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: