- PhoneGap 4 Mobile Application Development Cookbook
- Zainul Setyo Pamungkas
- 963字
- 2021-07-09 21:26:48
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:
- First, create a new PhoneGap project named
geoupdate
by running the following command:phonegap create geoupdate com.myapp.geoupdate geoupdate
- 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 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>
- Below the Cordova JavaScript reference, write a new JavaScript tag block. Within this, declare a new variable called
watchID
. - 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>
- Now add the
onDeviceReady
function, which will execute a method calledstartWatch
:// The device is ready so let's // start watching the position function onDeviceReady() { startWatch(); }
- You can now create the
startWatch
function. First, create theoptions
variable to hold the optional parameters that can be passed through to the method. Setfrequency
to 5,000 milliseconds (five seconds) and setenableHighAccuracy
totrue
. - Next, assign the
watchPosition
to the previously defined variablewatchID
. This variable will be used to check if the location is currently being watched. - To pass through the extra parameters that have been set, send the
options
variable into thewatchPosition
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); }
- With the initial call methods created, you can now write the
onSuccess
function, which is executed after a successful response. Theposition
object from the response is sent through as an argument to the function. - Declare some variables to store detailed information obtained from the response in the form of the
timestamp
,latitude
,longitude
, andaccuracy
variables. Then, create the element variable to reference thegeolocationData
div
element, within which the information will be displayed. - The returned information is then assigned to the relevant variables by accessing the properties from the
position
object. - 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 />'; }
- With the
onSuccess
method created, now write theonError
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; }
- Upon running the application, the output will be similar to the following:
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 aBoolean
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 totrue
, more accurate methods will be used to locate the device, using satellite positioning, for example.timeout
: This is aNumber
that defines the maximum length of time in milliseconds to obtain the successful response.maximumAge
: This is aNumber
that defines if a coached position younger than the specified time in milliseconds can be used.
- Learning NServiceBus(Second Edition)
- PWA入門與實踐
- Python for Secret Agents:Volume II
- Access 2016數據庫管
- Instant Lucene.NET
- Visual Basic程序設計上機實驗教程
- Terraform:多云、混合云環境下實現基礎設施即代碼(第2版)
- Scala Reactive Programming
- HTML5從入門到精通(第4版)
- Learning Hadoop 2
- 監控的藝術:云原生時代的監控框架
- 邊玩邊學Scratch3.0少兒趣味編程
- 大學計算機應用基礎(Windows 7+Office 2010)(IC3)
- Koa與Node.js開發實戰
- Learning Alfresco Web Scripts