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

Obtaining device geolocation sensor information

Geolocation and the use of Global Positioning System (GPS) allow developers to create dynamic real-time mapping, positioning, and tracking applications. Using the available geolocation methods, we can retrieve a detailed set of information and properties to create location-aware applications. We can obtain the user's location via the mobile data network, Wi-Fi, or directly from the satellite.

How to do it…

We will use the geolocation functionality from the geolocation plugin's API to monitor the feedback from the device and obtain the relevant location information, as follows:

  1. First, create a new PhoneGap project named geolocation. Open Terminal or Command Prompt and run following command:
    phonegap create geolocation com.myapp.geolocation geolocation
    
  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 the 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>Geolocation</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. Write a new JavaScript tag block beneath the Cordova JavaScript reference. Within this, define an event listener to ensure the device is ready:
    <script type="text/javascript">
        // Set the event listener to run when the device is ready
        document.addEventListener("deviceready", onDeviceReady, false);
    </script>
  6. Now add the onDeviceReady function. This will execute the geolocation.getCurrentPosition method from the PhoneGap API once the native code has fully loaded:
    // The device is ready so let's
    // obtain the current geolocation data
    function onDeviceReady() {
        navigator.geolocation.getCurrentPosition(
        onSuccess, onError);
    }
  7. Include the onSuccess function to handle the returned the position object from the geolocation request.
  8. Then, create a reference to the geolocationData div element and assign it to the geoElement variable, which will hold the generated position results.
  9. Next, assign the returned values as a formatted string, which will be set as the HTML content within the geolocationData div element. The available properties are accessed through the position object:
    // Run after successful transaction
    // Let's display the position data
    function onSuccess(position) {
    
        var geoElement = document.getElementById('geolocationData');
    
        geoElement .innerHTML = 'Latitude: '  + position.coords.latitude + '<br />' +
         'Longitude: ' + position.coords.longitude + '<br />' +
         'Altitude: '  + position.coords.altitude + '<br />' +
         'Accuracy: '  + position.coords.accuracy + '<br />' +
         'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
         'Heading: ' + position.coords.heading  + '<br />' +
         'Speed: '   + position.coords.speed + '<br />' +
         'Timestamp: ' + position.timestamp + '<br />';
    }
  10. Finally, include the onError function to handle any possible errors that may arise.
  11. Depending on the existence of an error, use the value of the returned error code to determine which message to display to the user. This will be set as the HTML content of the geolocationData div element:
    // 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 due to an unknown error.';
                break;
            }
    
        }
    
        // Handle any errors we may face
        var element = document.getElementById('geolocationData');
        element.innerHTML = errString;
    
    }
  12. When running the application on a device, the output will look something like this:
    How to do it…
  13. If you face any errors, the resulting output will look something like this:
    How to do it…

How it works…

As soon as the device is ready and the native PhoneGap code has been initiated on the device, the application will execute the getCurrentPosition method from the geolocation API. We have defined an onSuccess method to manage the output and handling of a successful response, and we have also specified an onError method to catch any errors and act accordingly.

The onSuccess method returns the obtained geolocation information in the form of the position object, which contains the following properties:

  • position.coords.speed: This is a Coordinates object that holds the geographic information returned from the request. This object contains the following properties:
    • latitude: This is a Number ranging from -90.00 to +90.00 that specifies the latitude estimate in decimal degrees.
    • longitude: This is a Number ranging from -180.00 to +180.00 that specifies the longitude estimate in decimal degrees.
    • altitude: This is a Number that specifies the altitude estimate in meters above the World Geodetic System (WGS) 84 ellipsoid. Optional.
    • accuracy: This Number specifies the accuracy of the latitude and longitude in meters. Optional.
    • altitudeAccuracy: This is a Number that specifies the accuracy of the altitude estimate in meters. Optional.
    • heading: This is a Number that specifies the current direction of movement in degrees, counting clockwise in relation to true north. Optional.
    • speed: This Number specifies the current ground speed of the device in meters per second. Optional.
  • position.timestamp: A DOMTimeStamp that signifies the time that the geolocation information was received and the position object was created.

The properties available within the position object are quite comprehensive and detailed. For those marked as optional, the value will be set and returned as null if the device cannot provide a value.

The onError method returns a PositionError object if an error is detected during the request. This object contains the following two properties:

  • code: This is a Number that contains a numeric code for the error.
  • message: This is a String that contains a human readable description of the error.

The errors could relate to insufficient permissions needed to access the geolocation sensors on the device, the inability to locate the device due to issues with obtaining the necessary GPS information, a timeout on the request, or the occurrence of an unknown error.

There's more...

The exposed geolocation API accessible through the geolocation plugin is based on the W3C geolocation API specification. Many modern browsers and devices already have this functionality enabled. If any device your application runs on already implements this specification, it will use the built-in support for the API and not the geolocation plugin's implementation.

See also

主站蜘蛛池模板: 光泽县| 通江县| 阳山县| 汉沽区| 盐山县| 正镶白旗| 本溪市| 航空| 双柏县| 镇康县| 谷城县| 枞阳县| 霸州市| 新化县| 阿城市| 望谟县| 白山市| 贵德县| 开封县| 五大连池市| 六安市| 芜湖市| 达拉特旗| 深水埗区| 贵港市| 江阴市| 商丘市| 五大连池市| 个旧市| 博客| 洛宁县| 简阳市| 林周县| 江达县| 巴林左旗| 安丘市| 柞水县| 海林市| 杭锦旗| 乌拉特前旗| 宁远县|