- PhoneGap 4 Mobile Application Development Cookbook
- Zainul Setyo Pamungkas
- 1072字
- 2021-07-09 21:26:47
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:
- First, create a new PhoneGap project named
geolocation
. Open Terminal or Command Prompt and run following command:phonegap create geolocation com.myapp.geolocation geolocation
- Add the device platform. You can choose to use Android, iOS, or both:
cordova platform add ios cordova platform add android
- Add the geolocation plugin by running the following command:
phonegap plugin add org.apache.cordova.geolocation
- 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>
- 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>
- Now add the
onDeviceReady
function. This will execute thegeolocation.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); }
- Include the
onSuccess
function to handle the returned theposition
object from the geolocation request. - Then, create a reference to the
geolocationData
div
element and assign it to thegeoElement
variable, which will hold the generated position results. - 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 theposition
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 />'; }
- Finally, include the
onError
function to handle any possible errors that may arise. - 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; }
- When running the application on a device, the output will look something like this:
- If you face any errors, the resulting output will look something like this:
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 aCoordinates
object that holds the geographic information returned from the request. This object contains the following properties:latitude
: This is aNumber
ranging from -90.00 to +90.00 that specifies the latitude estimate in decimal degrees.longitude
: This is aNumber
ranging from -180.00 to +180.00 that specifies the longitude estimate in decimal degrees.altitude
: This is aNumber
that specifies the altitude estimate in meters above the World Geodetic System (WGS) 84 ellipsoid. Optional.accuracy
: ThisNumber
specifies the accuracy of the latitude and longitude in meters. Optional.altitudeAccuracy
: This is aNumber
that specifies the accuracy of the altitude estimate in meters. Optional.heading
: This is aNumber
that specifies the current direction of movement in degrees, counting clockwise in relation to true north. Optional.speed
: ThisNumber
specifies the current ground speed of the device in meters per second. Optional.
position.timestamp
: ADOMTimeStamp
that signifies the time that the geolocation information was received and theposition
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 aNumber
that contains a numeric code for the error.message
: This is aString
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
- You can find out more about geolocation and the
getCurrentPosition
method via the official Cordova documentation available at http://plugins.cordova.io/#/package/org.apache.cordova.geolocation.
- Mastering Ext JS(Second Edition)
- 手機安全和可信應用開發指南:TrustZone與OP-TEE技術詳解
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- 深入淺出Windows API程序設計:編程基礎篇
- Vue.js 3.0源碼解析(微課視頻版)
- HTML5 and CSS3 Transition,Transformation,and Animation
- HTML5入門經典
- Getting Started with Gulp
- Creating Stunning Dashboards with QlikView
- D3.js By Example
- Advanced Express Web Application Development
- Java零基礎實戰
- C語言程序設計習題與實驗指導
- Mastering AWS Security
- 深度學習原理與PyTorch實戰(第2版)