Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Monitored positioning CHAPTER 14 547


<head>
<title></title>
<link href="GeoLocation.css" rel="stylesheet" />
<script src="Scripts/jquery-1.8.3.js"></script>
<script src="Scripts/GeoLocation.js"></script>
</head>
<body>
<div id="message">
</div>
<button id="startMonitoring">Start Monitoring</button>
<button id="stopMonitoring">Stop Monitoring</button>
</body>
</html>
With the added buttons and the change to use the watchPosition method, the following is
the updated JavaScript; the notable changes are in bold.
/// <reference path="jquery-1.8.3.js" />

var watchId = 0;

$(document).ready(function () {
$(‘#startMonitoring’).on(‘click’, getLocation);
$(‘#stopMonitoring’).on(‘click’, endWatch);
});

function supportsGeolocation() {
return 'geolocation' in navigator;
}

function showMessage(message) {
$('#message').html(message);
}

function getLocation() {
if (supportsGeolocation()) {
var options = {
enableHighAccuracy: true
};
watchId = navigator.geolocation.watchPosition(showPosition, showError, options);
}
else {
showMessage("Geolocation is not supported by this browser.");
}
}

function endWatch() {
if (watchId != 0) {
navigator.geolocation.clearWatch(watchId);
watchId = 0;
showMessage("Monitoring ended.");
}
}

function showPosition(position) {
Free download pdf