Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

548 CHAPTER 14 Making your HTML location-aware


var datetime = new Date(position.timestamp).toLocaleString();
showMessage("Latitude: " + position.coords.latitude + "<br />"
+ "Longitude: " + position.coords.longitude + "<br />"
+ "Timestamp: " + datetime);
}

function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
showMessge("User denied Geolocation access request.");
break;
case error.POSITION_UNAVAILABLE:
showMessage("Location information unavailable.");
break;
case error.TIMEOUT:
showMessage("Get user location request timed out.");
break;
case error.UNKNOWN_ERROR:
showMessage("An unknown error occurred.");
break;
}
}
This code doesn’t require many changes to get the benefit of continuous monitoring. The
big change is the addition of the endWatch function that uses the watchId global variable to
stop location monitoring.

Calculating distance between samples


When you’re continuously monitoring the user’s location, you might want to calculate the
distance between samples.
Calculating the distance traveled is relatively easy if you are traveling over a flat plane.
Because people are traveling over the earth, you need to use spherical geometry to calcu-
late the distance traveled. There are several formulas for this calculation, based primarily on
accuracy. In addition, all calculations are based on the earth being perfectly round with no
hills and valleys.
This example shows implementation of the haversine formula to calculate the distance.
This formula is a bit more complex than other formulas, such as the spherical law of cosines,
but it provides better accuracy. The following is a getDistance function using the haversine
formula.
function getDistance(lat1, lon1, lat2, lon2) {
var earthRadius = 3959; //miles
var latRadians = getRadians(lat2 - lat1);
var lonRadians = getRadians(lon2 - lon1);
var a = Math.sin(latRadians / 2) * Math.sin(latRadians / 2) +
Math.cos(getRadians(lat1)) * Math.cos(getRadians(lat2)) *
Math.sin(lonRadians / 2) * Math.sin(lonRadians / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var distance = earthRadius * c;
Free download pdf