HTML5 Game - Getting the Current Position

Introduction

The getCurrentPosition method from navigator.geolocation returns the current position.

We supply a success callback function which is invoked when the position information is available.

The following code shows how we can get the position information using this method.

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>
        </table>
        <script>        
            navigator.geolocation.getCurrentPosition(displayPosition);
            //  w w w  . j a  v  a2s .c  o  m
            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;
            }
        </script>
    </body>
</html>

The example calls the getCurrentPosition, passing the displayPosition function as the method argument.

When the position information is available, the function is invoked and the browser passes in a Position object.

Related Topic