25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

226<br />

CHAPTER 9 ■ USING THE <strong>HTML</strong>5 WEB STORAGE API<br />

function distance(latitude1, longitude1, latitude2, longitude2) {<br />

// R is the radius of the earth in kilometers<br />

var R = 6371;<br />

var deltaLatitude = toRadians((latitude2-latitude1));<br />

var deltaLongitude = toRadians((longitude2-longitude1));<br />

latitude1 = toRadians(latitude1), latitude2 = toRadians(latitude2);<br />

var a = Math.sin(deltaLatitude/2) *<br />

Math.sin(deltaLatitude/2) +<br />

Math.cos(latitude1) *<br />

Math.cos(latitude2) *<br />

Math.sin(deltaLongitude/2) *<br />

Math.sin(deltaLongitude/2);<br />

var c = 2 * Math.atan2(Math.sqrt(a),<br />

Math.sqrt(1-a));<br />

var d = R * c;<br />

return d;<br />

}<br />

// latitude and longitude for the finish line in the Lake Tahoe race<br />

var finishLat = 39.17222;<br />

var finishLong = -120.13778;<br />

In this familiar set of functions—used earlier in Chapter 6—we calculate the distance between two<br />

points with a distance function. The details are not of particular importance, nor are they the most<br />

accurate representation of distance along a racetrack, but they’ll do for our example.<br />

In the final lines, we establish a latitude and longitude for the finish line location of the race. As<br />

you’ll see, we will compare these coordinates with incoming racer positions to determine the racers’<br />

distance from the finish line, and thus, their ranks in the race.<br />

Now, let’s look at a tiny snippet of the <strong>HTML</strong> markup used to display the page.<br />

Live T216 Leaderboard<br />

Leaderboard: Connecting...<br />

<br />

Although most of the page <strong>HTML</strong> is irrelevant to our demonstration, in these few lines, we declare<br />

some named elements with the IDs leaderboardStatus and leaderboard. The leaderboardStatus is<br />

where we will display the connection information for our WebSocket. And the leaderboard itself is where<br />

we will insert div elements to indicate the position information we are receiving from our WebSocket<br />

messages, using the utility function shown in Listing 9-6.<br />

Listing 9-6. Position Information Utility Function<br />

// display the name and distance in the page<br />

function displayRacerLocation(name, distance) {<br />

// locate the <strong>HTML</strong> element for this ID<br />

// if one doesn't exist, create it<br />

var incomingRow = document.getElementById(name);<br />

if (!incomingRow) {

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

Saved successfully!

Ooh no, something went wrong!