Watching the Position Change over Time

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.

NOTE Activating the GPS on a mobile device (which is what you are effectively requesting by turning on enableHighAccuracy) drains the battery, so be courteous to your users and use watches only when you must update the position.

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.