Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

CHAPTER 5 USING THE GEOLOCATION API

Sitting here in my backyard hammock on a lazy afternoon, I monitored my position on a geolocation– enabled cell phone browser. I was surprised to see that over the course of only a few minutes, my reclined body was reported to travel half a kilometer in distance at varying speeds. As exciting as this might sound, it is a reminder that data is only as accurate as its source permits.”

Finally, we will calculate the distance traveled, assuming that we have already received at least one accurate position value before. We will update the totals of travel distance and display them for the user, and we will store the current values for future comparison. To keep our interface a little less cluttered, it is a good idea to round or truncate the calculated values, as shown in Listing 5-13.

Listing 5-13. Adding the Distance Calculation Code

// calculate distance

if ((lastLat != null) && (lastLong != null)) {

var currentDistance = distance(latitude, longitude, lastLat, lastLong); document.getElementById("currDist").innerHTML =

"Current distance traveled: " + currentDistance.toFixed(2) + " km"; totalDistance += currentDistance; document.getElementById("totalDist").innerHTML =

"Total distance traveled: " + currentDistance.toFixed(2) + " km"; updateStatus("Location successfully updated.");

}

lastLat = latitude; lastLong = longitude;

}

That’s it. In fewer than 200 lines of HTML and script, we’ve created a sample application that monitors the viewer’s position over time and demonstrated nearly the entire Geolocation API, complete with error handling. Although this example is inherently less interesting when viewed on a desktop computer, try it out on your favorite geolocation–enabled phone or device and see how mobile you truly are during the course of a day.

The Final Code

The full code sample is shown in Listing 5-14.

Listing 5-14. Complete Distance Tracker Code

<!DOCTYPE html> <html>

<head>

<meta charset="utf-8" > <title>Geolocation</title>

<link rel="stylesheet" href="geo-html5.css" > </head>

126

CHAPTER 5 USING THE GEOLOCATION API

<body onload="loadDemo()">

<header>

<h1>Odometer Demo</h1> <h4>Live Race Data!</h4>

</header>

<div id="container">

<section>

<article>

<header>

<h1>Your Location</h1> </header>

<p class="info" id="status">Geolocation is not supported in your browser.</p>

<div class="geostatus">

<p id="latitude">Latitude: </p> <p id="longitude">Longitude: </p> <p id="accuracy">Accuracy: </p> <p id="timestamp">Timestamp: </p>

<p id="currDist">Current distance traveled: </p> <p id="totalDist">Total distance traveled: </p>

</div>

</article>

</section>

<footer>

<h2>Powered by HTML5, and your feet!</h2> </footer>

</div>

<script>

var totalDistance = 0.0; var lastLat;

var lastLong;

Number.prototype.toRadians = function() { return this * Math.PI / 180;

}

function distance(latitude1, longitude1, latitude2, longitude2) { // R is the radius of the earth in kilometers

var R = 6371;

var deltaLatitude = (latitude2-latitude1).toRadians(); var deltaLongitude = (longitude2-longitude1).toRadians();

latitude1 = latitude1.toRadians(), latitude2 = latitude2.toRadians();

127

CHAPTER 5 USING THE GEOLOCATION API

var a = Math.sin(deltaLatitude/2) * Math.sin(deltaLatitude/2) + Math.cos(latitude1) * Math.cos(latitude2) * Math.sin(deltaLongitude/2) * Math.sin(deltaLongitude/2);

var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

var d = R * c; return d;

}

function updateErrorStatus(message) { document.getElementById("status").style.background = "papayaWhip"; document.getElementById("status").innerHTML = "<strong>Error</strong>: " + message;

}

function updateStatus(message) { document.getElementById("status").style.background = "paleGreen"; document.getElementById("status").innerHTML = message;

}

function loadDemo() {

if(navigator.geolocation) {

document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser.";

navigator.geolocation.watchPosition(updateLocation, handleLocationError, {timeout:10000});

}

}

function updateLocation(position) {

var latitude = position.coords.latitude; var longitude = position.coords.longitude; var accuracy = position.coords.accuracy; var timestamp = position.timestamp;

document.getElementById("latitude").innerHTML = "Latitude: " + latitude; document.getElementById("longitude").innerHTML = "Longitude: " + longitude; document.getElementById("accuracy").innerHTML = "Accuracy: " + accuracy + " meters"; document.getElementById("timestamp").innerHTML = "Timestamp: " + timestamp;

//sanity test... don't calculate distance if accuracy

//value too large

if (accuracy >= 30000) {

updateStatus("Need more accurate values to calculate distance."); return;

}

128