September 2012
Intermediate to advanced
552 pages
14h 48m
English
The geolocation API provides a second method called watchPosition that takes in the same parameters as getCurrentPosition. It works like setInterval in that it returns an ID that can be used to clear the watch at a later time with clearWatch.
If you want to walk around a bit, run the code in Listing 23-3, which uses watchPosition to log the latitude and longitude to a <div> on a mobile browser and see how the numbers change.
Listing 23-3: Watching the position change
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Watching the position</title>
<script src='js/jquery.min.js'></script>
</head>
<body>
<script>
function logPosition(position) {
$("#logs").prepend(position.coords.latitude + "," +
position.coords.latitude + "<br/>");
}
function positionError(error) {
console.log(error);
}
var watchID = navigator.geolocation.watchPosition(
logPosition,positionError,{
enableHighAccuracy: true
});
setTimeout(function() {
navigator.geolocation.clearWatch(watchID);
},30000);
</script>
<div id='logs'></div>
</body>
</html>
You can see that after 30 seconds the watch is cleared to prevent the system from continuing to update the position.
Read now
Unlock full access