HTML5 Game - Geolocation GeoLocaltion Monitoring

Introduction

We can receive ongoing updates about the position by using the watchPosition method.

This method takes the same arguments as the getCurrentPosition method.

The callback functions will be repeatedly called as the position changes.

The following code shows how we can use the watchPosition method.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <body>
        <table border="1">
            <tr>
                <th>Longitude:</th><td id="longitude">-</td>
                <th>Latitude:</th><td id="latitude">-</td>
            </tr>
            <tr>
                <th>Altitude:</th><td id="altitude">-</td>
                <th>Accuracy:</th><td id="accuracy">-</td>
            </tr>
            <tr>
                <th>Altitude Accuracy:</th><td id="altitudeAccuracy">-</td>
                <th>Heading:</th><td id="heading">-</td>
            </tr>
            <tr>
                <th>Speed:</th><td id="speed">-</td>
                <th>Time Stamp:</th><td id="timestamp">-</td>
            </tr>
            <tr>
                <th>Error Code:</th><td id="errcode">-</td>
                <th>Error Message:</th><td id="errmessage">-</td>
            </tr>            
        </table>
        <button id="pressme">Cancel Watch</button>
        <script>        
            //w  w w  .  ja v  a 2s . c  o  m
            let options = {
                enableHighAccuracy: false,
                timeout: 2000,
                maximumAge: 30000
            };
            
            let watchID = navigator.geolocation.watchPosition(displayPosition,
                                                     handleError,
                                                     options);
            
            document.getElementById("pressme").onclick = function(e) {
                navigator.geolocation.clearWatch(watchID);
            };
            
            function displayPosition(pos) {
                let properties = ["longitude", "latitude", "altitude", "accuracy",
                                  "altitudeAccuracy", "heading", "speed"];
                
                for (let i = 0; i < properties.length; i++) {
                    let value = pos.coords[properties[i]];
                    document.getElementById(properties[i]).innerHTML = value;
                }
                document.getElementById("timestamp").innerHTML = pos.timestamp;
            }
            
            function handleError(err) {
                document.getElementById("errcode").innerHTML = err.code;
                document.getElementById("errmessage").innerHTML = err.message;
            }
            
        </script>
    </body>
</html>

The code uses the watchPosition method to monitor the location.

This method returns an ID value which we can pass to the clearWatch method when we want to stop monitoring.

Related Topics