C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-orientation
如果你有學習我們前面教學,你可能會注意到,這個外掛它類似於加速度外掛。我們在本教學中使用的是同一個概念。讓我們在 index.html 檔案中建立兩個按鈕
<button id = "getOrientation">GET ORIENTATION</button> <button id = "watchOrientation">WATCH ORIENTATION</button>
document.getElementById("getOrientation").addEventListener("click", getOrientation); document.getElementById("watchOrientation").addEventListener("click", watchOrientation);
我們將建立兩個函式,一個來獲取當前加速度,另外一個用來監視方向的變化。可以看到再次使用頻率選項,因為我們希望每三秒鐘觀察其變化。
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); }; }
由於指南針外掛幾乎與加速度外掛是一樣的,這次我們告訴你錯誤程式碼。一些裝置不具有指南針工作所需要的磁感測器。如果您的裝置沒有,會得到下面的錯誤。