25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

106<br />

CHAPTER 4 ■ USING THE <strong>HTML</strong>5 GEOLOCATION API<br />

Note also that we are setting a maximumAge option on our position watch: {maximumAge:20000}. This<br />

will tell the location service that we don’t want any cached location values that are greater than 20<br />

seconds (or 20000 milliseconds) old. Setting this option will keep our page updating at regular intervals,<br />

but feel free to adjust this number and experiment with larger and smaller cache sizes.<br />

The bulk of our work will be done in our updateLocation() function. Here we will update the page<br />

with our most recent values and calculate the distance traveled, as shown in Listing 4-11.<br />

Listing 4-11. Adding the updateLocation() function<br />

function updateLocation(position) {<br />

var latitude = position.coords.latitude;<br />

var longitude = position.coords.longitude;<br />

var accuracy = position.coords.accuracy;<br />

var timestamp = position.timestamp;<br />

document.getElementById("latitude").inner<strong>HTML</strong> = latitude;<br />

document.getElementById("longitude").inner<strong>HTML</strong> = longitude;<br />

document.getElementById("accuracy").inner<strong>HTML</strong> = accuracy;<br />

document.getElementById("timestamp").inner<strong>HTML</strong> = timestamp;<br />

As you might expect, the first thing we will do when we receive an updated set of position<br />

coordinates is to record all the information. We gather the latitude, longitude, accuracy, and timestamp,<br />

and then update the table values with the new data.<br />

You might not choose to display a timestamp in your own application. The timestamp number used<br />

here is in a form primarily useful to computers, which won’t be meaningful to an end user. Feel free to<br />

replace it with a more user-friendly time indicator or remove it altogether.<br />

The accuracy value is given to us in meters and might at first seem unnecessary. However, any data<br />

depends on its accuracy. Even if you don’t present the user with the accuracy values, you should take<br />

them into account in your own code. Presenting inaccurate values could give the user a skewed idea of<br />

his or her location. Therefore, we will throw out any position updates with an unreasonably low<br />

accuracy, as shown in Listing 4-12.<br />

Listing 4-12. Ignoring inaccurate accuracy updates<br />

}<br />

// sanity test... don't calculate distance if accuracy<br />

// value too large<br />

if (accuracy >= 500) {<br />

updateStatus("Need more accurate values to calculate distance.");<br />

return;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!