官术网_书友最值得收藏!

Adjusting the geolocation sensor update interval

Through the use of the getCurrentPosition method, we can retrieve a single reference to the device location using GPS coordinates. In this recipe, we'll create the functionality to obtain the current location based on a numeric interval to receive constantly updated information.

How to do it…

We are able to pass through an optional parameter containing various arguments to set up interval and improve accuracy:

  1. First, create a new PhoneGap project named geoupdate by running the following command:
    phonegap create geoupdate com.myapp.geoupdate geoupdate
    
  2. Add the device platform. You can choose to use Android, iOS, or both:
    cordova platform add ios
    cordova platform add android
    
  3. Add the geolocation plugin by running the following command:
    phonegap plugin add org.apache.cordova.geolocation
    
  4. Open www/index.html and clean up unnecessary elements; so you have the following:
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <meta name="format-detection" content="telephone=no" />
            <meta name="msapplication-tap-highlight" content="no" />
            <!-- WARNING: for iOS 7, remove the
    width=device-width and height=device-height attributes.
    See https://issues.apache.org/jira/browse/CB-4323 -->
            <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height,
    target-densitydpi=device-dpi" />
            <title>Geoupdate</title>
        </head>
        <body>
            <h1>Geolocation Data</h1>
    
            <div id="geolocationData">Obtaining data...</div>
    
            <script type="text/javascript" src="cordova.js"></script>
            <script type="text/javascript">
    
            </script>
        </body>
    </html>
  5. Below the Cordova JavaScript reference, write a new JavaScript tag block. Within this, declare a new variable called watchID.
  6. Next, write the event listener to continue once the device is ready:
    <script type="text/javascript">
        // The watch id variable is set as a
        // reference to the current 'watchPosition'
        var watchID = null;
        // Set the event listener to run
        // when the device is ready
        document.addEventListener("deviceready", onDeviceReady, false);
    </script>
  7. Now add the onDeviceReady function, which will execute a method called startWatch:
    // The device is ready so let's
    // start watching the position
    function onDeviceReady() {
        startWatch();
    }
  8. You can now create the startWatch function. First, create the options variable to hold the optional parameters that can be passed through to the method. Set frequency to 5,000 milliseconds (five seconds) and set enableHighAccuracy to true.
  9. Next, assign the watchPosition to the previously defined variable watchID. This variable will be used to check if the location is currently being watched.
  10. To pass through the extra parameters that have been set, send the options variable into the watchPosition method:
    function startWatch() {
    
        // Create the options to send through
        var options = {
                enableHighAccuracy: true
        };
    
        // Watch the position and update
        // when a change has been detected
        watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
    
    }
  11. With the initial call methods created, you can now write the onSuccess function, which is executed after a successful response. The position object from the response is sent through as an argument to the function.
  12. Declare some variables to store detailed information obtained from the response in the form of the timestamp, latitude, longitude, and accuracy variables. Then, create the element variable to reference the geolocationData div element, within which the information will be displayed.
  13. The returned information is then assigned to the relevant variables by accessing the properties from the position object.
  14. Finally, apply the populated variables to a concatenated string and set it as the HTML within the div element:
    // Run after successful transaction
    // Let's display the position data
    function onSuccess(position) {
    
        var timestamp, latitude, longitude, accuracy;
    
        var element = document.getElementById('geolocationData');
    
        timestamp   =   new Date(position.timestamp);
        latitude    =   position.coords.latitude;
        longitude   =   position.coords.longitude;
        accuracy        =   position.coords.accuracy;
    
        element.innerHTML +=
                '<hr />' +
                'Timestamp: '   + timestamp + '<br />' +
                'Latitude: '    + latitude  + '<br />' +
                'Longitude: '   + longitude + '<br />' +
                'Accuracy: '    + accuracy  + '<br />';
    }
  15. With the onSuccess method created, now write the onError function to handle any errors that you may face following the response:
    // Run if we face an error
    // obtaining the position data
    function onError(error) {
    
        var errString   =   '';
    
        // Check to see if we have received an error code
        if(error.code) {
            // If we have, handle it by case
            switch(error.code)
            {
                case 1: // PERMISSION_DENIED
                    errString   =
                'Unable to obtain the location information ' +
                'because the device does not have permission '+
                'to the use that service.';
                break;
                case 2: // POSITION_UNAVAILABLE
                    errString   =
                 'Unable to obtain the location information ' +
                 'because the device location could not be ' +
                 'determined.';
                break;
                case 3: // TIMEOUT
                    errString   =
                  'Unable to obtain the location within the ' +
                        'specified time allocation.';
                break;
                default: // UNKOWN_ERROR
                    errString   =
                    'Unable to obtain the location of the ' +
                    'device to an unknown error.';
                break;
            }
    
        }
    
        // Handle any errors we may face
        var element = document.getElementById('geolocationData');
        element.innerHTML = errString;
    
    }
  16. Upon running the application, the output will be similar to the following:
    How to do it…

How it works…

The watchPosition method from the PhoneGap API runs as an asynchronous function, constantly checking for changes to the device's current position. Once a change in position has been detected, it will return the current geographic location information in the form of the position object.

With every successful request made on the continuous cycle, the onSuccess method is executed, and it formats the data for output onto the screen.

There's more…

There are three optional parameters that can be sent into either the getCurrentPosition or watchPosition methods, which are:

  • enableHighAccuracy: This is a Boolean that specifies whether or not you would like to obtain the best possible location results from the request. By default (false), the position will be retrieved using the mobile or cell network. If set to true, more accurate methods will be used to locate the device, using satellite positioning, for example.
  • timeout: This is a Number that defines the maximum length of time in milliseconds to obtain the successful response.
  • maximumAge: This is a Number that defines if a coached position younger than the specified time in milliseconds can be used.

    Note

    Android devices will not return a successful geolocation result unless enableHighAccuracy is set to true.

Clearing the interval

To clear interval timer we can use the clearWatch method from the geolocation plugin API. The method to clear the interval and stop watching location data is identical to the method used when clearing accelerometer data obtained from continual updates.

主站蜘蛛池模板: 阳东县| 麻栗坡县| 远安县| 东丰县| 大同市| 黑龙江省| 永川市| 张家界市| 华阴市| 肃宁县| 广安市| 秭归县| 山东省| 清水县| 普格县| 浦北县| 大竹县| 织金县| 蕉岭县| 外汇| 武隆县| 洪洞县| 定襄县| 辽中县| 天镇县| 兴化市| 西城区| 宜兰市| 都兰县| 固原市| 当雄县| 玛沁县| 栖霞市| 西林县| 宝应县| 伊通| 汕尾市| 冕宁县| 申扎县| 桦川县| 邳州市|