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.

Listing 4-6. The Haversine formula<br />

� �<br />

� = 2arcsin sin 2� �� �<br />

� � + cos�<br />

� 2 �<br />

scos� f sin 2 �<br />

� ���<br />

�<br />

� �<br />

� � �<br />

�<br />

� 2 � �<br />

�<br />

�<br />

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

If you're hoping to learn how the Haversine formula works, you’ll be sorely disappointed. Instead,<br />

we’ll present you a JavaScript implementation of the formula, which allows anyone to use it to calculate<br />

the distance between two positions (see Listing 4-7).<br />

Listing 4-7. A JavaScript Haversine implementation<br />

function toRadians(degree) {<br />

return degree * Math.PI / 180;<br />

}<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);<br />

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 />

If you want to know why or how this formula works, consult a teenager’s math textbook. For our<br />

purposes, we have written a conversion from degrees to radians, and we provided a distance() function<br />

to calculate the distance between two latitude and longitude position values.<br />

If we check the user’s position and calculate the distance traveled at frequent and regular intervals,<br />

it gives a reasonable approximation of distance traveled over time. This assumes that the user is moving<br />

in a straight direction during each interval, but we’ll make that assumption for the sake of our example.<br />

103

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

Saved successfully!

Ooh no, something went wrong!