HTML5 Game - Geolocation Geolocation Options

Introduction

The third argument for the getCurrentPosition method is a PositionOptions object.

We can control the way that locations are obtained.

The following table shows the properties that this object defines.

Name
Description
Returns
enableHighAccuracy
get the best possible result
boolean
timeout

Sets a limit on how many milliseconds a position request
can take before a timeout error is reported
number

maximumAge

location which is not older than the specified number
of milliseconds
number

The following code shows how we can use the PositionOptions object when requesting a location.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            table {border-collapse: collapse;}
            th, td {padding: 4px;}
            th {text-align: right;}
        </style>
    </head>
    <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>
        <script>        
            /*from   ww  w  .j  a v a  2  s .c  om*/
            let options = {
                enableHighAccuracy: false,
                timeout: 2000,
                maximumAge: 30000
            };
            
            navigator.geolocation.getCurrentPosition(displayPosition,
                                                     handleError, options);
            
            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>

Related Topics