'Small Devices/Mobile'에 해당되는 글 14건

  1. 2012.10.09 [Phonegap] Compass 이용하기
반응형

Compass는 디바이스가 가르키는 위치를 알려준다. 다음의 메소드들이 존재한다.

compass.getCurrentHeading

compass.watchHeading

compass.clearWatch

compass.watchHeadingFilter (obsolete)

compass.clearWatchFilter (obsolete)


1. compass.getCurrentHeading

현재 Compass가 가르키는 방향을 알려준다. 0-359.99의 값을 리턴한다.


navigator.compass.getCurrentHeading(compassSuccess,compassError,compassOptions);


다음은 그 예제이다.

 <!DOCTYPE html>

<html>

  <head>

    <title>Compass Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>

    <script type="text/javascript" charset="utf-8">

    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {

        var headingButton=document.getElementById("getHeading");

        headingButton.addEventListener("click",getHeadingFunc,false);

    }

    function getHeadingFunc(){

        navigator.compass.getCurrentHeading(onSuccess, onError);

    }

    function onSuccess(heading) {

        alert('Heading: ' + heading.magneticHeading);

    }

    function onError(compassError) {

        alert('Compass Error: ' + compassError.code);

    }

    </script>

  </head>

  <body>

    <h1>Example</h1>

    <button id="getHeading">getCurrentHeading</button>

  </body>

</html>

다음은 실행 결과 이다.



2. compass.watchHeading & compass.clearWatch

주기적으로 방향을 체크하여 compassSuccess를 호출한다. compass.clearWatch는 주기적 체크를 중지한다. compassOptions의 frequency 값으로 체크 주기를 설정한다.


var watchID = navigator.compass.watchHeading(compassSuccess, 

compassError, [compassOptions]);


다음은 그 예제이다.

 

<!DOCTYPE html>

<html>

  <head>

    <title>Compass Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script>

    <script type="text/javascript" charset="utf-8">

    var watchID = null;

    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {

        startWatch();

    }

    function startWatch() {

        var options = { frequency: 1000 };

        watchID = navigator.compass.watchHeading(onSuccess, onError, options);

    }

    function stopWatch() {

        if (watchID) {

            navigator.compass.clearWatch(watchID);

            watchID = null;

        }

    }

    function onSuccess(heading) {

        var element = document.getElementById('heading');

        element.innerHTML = 'Heading: ' + heading.magneticHeading;

    }

    function onError(compassError) {

        alert('Compass error: ' + compassError.code);

    }


    </script>

  </head>

  <body>

    <div id="heading">Waiting for heading...</div>

    <button onclick="startWatch();">Start Watching</button>

    <button onclick="stopWatch();">Stop Watching</button>

  </body>

</html>

다음은 실행 결과이다.



반응형
Posted by alias
,