Geolocation

The geolocation plugin provides information about the device's current location that can be retrieved via Global Positioning System (GPS), network signals, and GSM/CDMA cell IDs. Note that there is no guarantee that the API returns the device's actual location.

In order to use the geolocation plugin in our Apache Cordova project, we need to use the following cordova plugin add command:

> cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git

Demo

In order to access the geolocation demo, you can click on the Geolocation list item. You will be introduced to the Geolocation page. You can click on the Get Current Position button in order to get your device's current position, as shown in the following screenshot:

Demo

Getting the device's position

The HTML page

The following code snippet shows the "geolocation" page:

<div data-role="page" id="geolocation">
    <div data-role="header">
        <h1>Geolocation</h1>
        <a href="#" data-role="button" data-rel="back" data-icon="back">Back</a>
    </div>
    <div data-role="content">
        <h1>Welcome to the Geolocation Gallery</h1>
        <p>Click 'Get Current Position' button below to know where you are.</p>
        <input type="button" id="getCurrentPosition" value="Get Current Position"/><br/>
    
        <div id="position">
        </div>
    </div>
</div>

As shown in the preceding "geolocation" page code snippet, it contains the following:

  • A page header that includes a back button
  • Page content that includes a "getCurrentPosition" button to get the device's current position and a "position" div in order to display it

View controller

The following code snippet shows the "geolocation" page view controller JavaScript object that includes the event handlers of the page (geolocation.js):

(function() {
    var geolocationManager = GeolocationManager.getInstance();

    $(document).on("pageinit", "#geolocation", function(e) {
        e.preventDefault();

        $("#getCurrentPosition").on("tap", function(e) {
            e.preventDefault();

            var callback = {};

            callback.onSuccess = onSuccess;
            callback.onError = onError;

            geolocationManager.getCurrentPosition(callback);
        });
    });

    function onSuccess(position) {
        console.log("position is retrieved successfully");

        $("#position").html("Latitude: "  + position.coords.latitude + "<br />" +
                            "Longitude: " + position.coords.longitude);    
    }

    function onError(error) {
        $("#position").html("Error code: " + error.code + ", message: " + error.message);
    }     
})();

As shown in the preceding code snippet, the "pageinit" event handler registers the "tap" event handler on the "getCurrentPosition" button. In the "tap" event handler of the "getCurrentPosition" button, the device's current position is retrieved by calling the geolocationManager.getCurrentPosition() method.

The geolocationManager.getCurrentPosition(callback) method takes a callback object as a parameter that contains two attributes (onSuccess and onError) that refer to the following callbacks:

  • onSuccess(position): This callback will be called if the operation succeeds. It receives a position object (which represents the device's current position) as a parameter. Inside the success callback, the position's longitude and latitude information are displayed in the "position" div.
  • onError(error): This callback will be called if the operation fails. It receives an error object that contains the error information (error code and error message) as a parameter.

API

The following code snippet shows the geolocation manager JavaScript object that interacts with the Apache Cordova geolocation API (GeolocationManager.js):

var GeolocationManager = (function () {     
    var instance;

    function createObject() {
        return {
            getCurrentPosition: function (callback) {
                navigator.geolocation.getCurrentPosition(callback.onSuccess, 
callback.onError, 
                                                         {
timeout: 15000, 
enableHighAccuracy: true 
                                                         });
            }
        };
    };

    return {
        getInstance: function () {
            if (!instance) {
                instance = createObject();
            }

            return instance;
        }
    }; 
})(); 

As shown, GeolocationManager is a singleton object that has a single method, getCurrentPosition(callback), as highlighted in the preceding code. This method uses the Cordova navigator.geolocation.getCurrentPosition() method in order to retrieve the device's current position.

The navigator.geolocation.getCurrentPosition(geolocationSuccess, [geolocationError], [geolocationOptions]) method has the following parameters:

  • geolocationSuccess: This represents the successful callback that will be called when the operation succeeds. It receives a Position object that holds the current position information as a parameter. In GeolocationManager, geolocationSuccess is set to callback.onSuccess.
  • geolocationError: This is an optional parameter that represents the error callback that will be called when the operation fails. It receives a PositionError object that holds the error information (the code that represents the error code and the message that represents the error message) as a parameter. In GeolocationManager, geolocationError is set to callback.onError.
  • geolocationOptions: This is an optional parameter that represents the geolocation options.

The geolocationOptions object has the attributes shown in the following table:

Attribute name

Description

enableHighAccuracy

If this attribute is set to true, it informs the plugin to use more accurate methods in order to get the current position, such as satellite positioning. In GeolocationManager.getCurrentPosition(), enableHighAccuracy is set to true.

timeout

This represents the time in milliseconds after which the operation times out. In GeolocationManager.getCurrentPosition(), timeout is set to 15000.

maximumAge

This is the maximum time in milliseconds for cached position.

The Position object has the attributes shown in the following table:

Attribute name

Description

coords

This represents a Coordinates object that represents coordinates of the position.

timestamp

This represents the creation timestamp of coords.

The Coordinates object has the attributes shown in the following table:

Attribute name

Description

latitude

This represents the position's latitude. It is used in our geolocation example.

longitude

This represents the position's longitude. It is used in our geolocation example.

altitude

This represents the height of the position in meters above the ellipsoid.

accuracy

This represents the accuracy level of the latitude and longitude coordinates in meters.

altitudeAccuracy

This represents the accuracy level of the altitude coordinate in meters.

heading

This represents the direction of travel, specified in degrees, counting clockwise relative to true north.

speed

This represents the current ground speed of the device, specified in meters per second.

Note that navigator.geolocation has the following two more methods:

  • watchPosition(geolocationSuccess, [geolocationError], [geolocationOptions]): This can watch for changes in the device's current position. It returns a watch ID that should be used with clearWatch() to stop watching for changes in position.
  • clearWatch(watchID): This can stop watching the changes to the device's position referenced by the watchID parameter.

We are now done with the geolocation functionality in the Cordova Exhibition app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.194.106