- PhoneGap 4 Mobile Application Development Cookbook
- Zainul Setyo Pamungkas
- 1030字
- 2021-07-09 21:26:48
Creating a visual compass to show the device direction
The geolocation and accelerometer plugins' API provides developers with the ability to receive coordinate and heading information from the device. We can use this information to build a custom compass tool that responds to the device movement.
How to do it…
- First, create a new PhoneGap project named
compass
by running the following command:phonegap create compass com.myapp.compass compass
- Add the device platform. You can choose to use Android, iOS, or both:
cordova platform add ios cordova platform add android
- Add the
device-orientation
,device-motion
, andgeolocation
plugins by running the following command:phonegap plugin add org.apache.cordova.device-motion phonegap plugin add org.apache.cordova.geolocation phonegap plugin add org.apache.cordova.device-orientation
- 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" /> <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>Compass</title> </head> <body> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript"> // further code will be here </script> </body> </html>
- In this example, certain elements within the DOM will be referenced by class name. For this, the XUI JavaScript library (http://xuijs.com/) will be used. Add the
script
reference under thecordova
reference:<script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="xui.js"></script>
- Add a new
div
element within thebody
tag and give this theclass
attribute ofcontainer
. This will hold the compass elements for display. - The compass itself will be made up of two images. Both images will have an individual
class
name assigned to them, which will allow you to easily reference each of them within the JavaScript. Add these two within thecontainer
element. - Next, write a new
div
element below the images with theid
attribute set toheading
. This will hold the text output from the compass response:<body> <div class="container"> <img src="images/rose.png" class="rose" width="120" height="121" alt="rose" /> <img src="images/compass.png" class="compass" width="200" height="200" alt="compass" /> <div id="heading"></div> </div>
- With the initial layout complete, start writing the custom JavaScript code. First, define the
deviceready
event listener—asXUI
is being used, this differs a little from other recipes within this chapter:var headingDiv; x$(document).on("deviceready", function () { });
- When you have a result to output to the user of the application, you want the data to be inserted into the
div
tag with theheading
id
attribute.XUI
makes this a simple task; so update theheadingDiv
global variable to store this reference:x$(document).on("deviceready", function () { headingDiv = x$("#heading"); });
- Now include the requests to the PhoneGap compass methods. We'll actually call two within the same function. First, obtain the current heading of the device for instant data, and then make a request through to watch the device heading, making the request every tenth of a second by using the
frequency
parameter; this will provide continual updates to ensure the compass is correct:navigator.compass.getCurrentHeading(onSuccess, onError); navigator.compass.watchHeading(onSuccess, onError, {frequency: 100});
- Both of these requests use the same
onSuccess
andonError
method to handle output and data management. TheonSuccess
method will provide the returned data in the form of aheading
object. - You can use this returned data to set the HTML content of the heading element with the generated message string, using the
headingDiv
variable defined earlier. - The visual compass also needs to respond to the heading information. Using
XUI
'sCSS
method, you can alter thetransform
properties of the rose image to rotate using the returnedmagneticHeading
property. Here, reference the image by calling its individual class name,.rose
:// Run after successful transaction // Let's display the compass data function onSuccess(heading) { headingDiv.html( 'Heading: ' + heading.magneticHeading + '° ' + convertToText(heading.magneticHeading) + '<br />' + 'True Heading: ' + heading.trueHeading + '<br />' + 'Accuracy: ' + heading.headingAccuracy ); // Alter the CSS properties to rotate the rose image x$(".rose").css({ "-webkit-transform": "rotate(-" + heading.magneticHeading + "deg)", "transform": "rotate(-" + heading.magneticHeading + "deg)" }); }
- With the
onSuccess
handler in place, you now need to add theonError
method to output a user-friendly message should you encounter any problems obtaining information:// Run if we face an error // obtaining the compass data function onError() { headingDiv.html( 'There was an error trying to ' + 'locate your current bearing.' ); }
- When creating the message string in the
onSuccess
function, you made a call to a new function calledconvertToText
. This accepts themagneticHeading
value from theheading
object and converts it into a text representation of the direction for display. Include this function outside theXUI
deviceready
block:// Accept the magneticHeading value // and convert into a text representation function convertToText(mh) { var textDirection; if (typeof mh !== "number") { textDirection = ''; } else if (mh >= 337.5 || (mh >= 0 && mh <= 22.5)) { textDirection = 'N'; } else if (mh >= 22.5 && mh <= 67.5) { textDirection = 'NE'; } else if (mh >= 67.5 && mh <= 112.5) { textDirection = 'E'; } else if (mh >= 112.5 && mh <= 157.5) { textDirection = 'SE'; } else if (mh >= 157.5 && mh <= 202.5) { textDirection = 'S'; } else if (mh >= 202.5 && mh <= 247.5) { textDirection = 'SW'; } else if (mh >= 247.5 && mh <= 292.5) { textDirection = 'W'; } else if (mh >= 292.5 && mh <= 337.5) { textDirection = 'NW'; } else { textDirection = textDirection; } return textDirection; }
- Now provide some CSS to position the two images on the screen and ensure the rose image is overlaying the compass image. Add a new
<style>
tag in<head>
before the<title>
tag:<style type="text/css"> .container { position: relative; margin: 0 auto; width: 200px; overflow: hidden; } #heading { position: relative; font-size: 24px; font-weight: 200; text-shadow: 0 -1px 0 #eee; margin: 20px auto 20px auto; color: #111; text-align: center; } .compass { padding-top: 12px; } .rose { position: absolute; top: 53px; left: 40px; width: 120px; height: 121px; } </style> <title>Compass</title>
- Upon running the application on the device, the output will look something like this:
How it works…
The watchHeading
method from the PhoneGap API compass functionality retrieves periodic updates containing the current heading of the device at the interval specified as the value of the frequency
variable passed through. If no interval is declared, a default value of 100 milliseconds (one-tenth of a second) is used.
With every successful request made on the continuous cycle, the onSuccess
method is executed, and it formats the data for output onto the screen as well as making a change to the transform
property of the graphical element to rotate in accordance with the heading.
The onSuccess
method returns the obtained heading information in the form of the compassHeading
object, which contains the following properties:
magneticHeading
: This is aNumber
ranging from 0 to 359.99 that specifies a heading in degrees at a single moment in time.trueHeading
: ThisNumber
ranges from 0 to 359.99 and specifies the heading relative to the geographic North Pole in degrees.headingAccuracy
: This is aNumber
that indicates any deviation in degrees between the reported heading and the true heading values.timestamp
: This refers to the time in milliseconds at which the heading was determined.
See also
- Chapter 7, Working with XUI
- SPSS數據挖掘與案例分析應用實踐
- Linux核心技術從小白到大牛
- Python測試開發入門與實踐
- Java編程指南:基礎知識、類庫應用及案例設計
- 微信小程序開發解析
- Building an RPG with Unity 2018
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(高級進階篇)
- 碼上行動:用ChatGPT學會Python編程
- Learning Laravel's Eloquent
- PHP從入門到精通(第4版)(軟件開發視頻大講堂)
- C# and .NET Core Test Driven Development
- HTML+CSS+JavaScript網頁設計從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- R語言數據可視化:科技圖表繪制
- C++ Application Development with Code:Blocks
- Angular Design Patterns