HTML5 Game - Following a Moving Location with watchPosition

Description

Following a Moving Location with watchPosition

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>

<head>
    <style>
        #mapCanvas {/*from www  . j a  v  a2 s.  c  o m*/
            width: 300px;
            height: 200px;
            border-style: solid;
            border-width: 2px;
            margin: 22px 0;
        }
        #btnMap {
            float: left;
        }

        #location {
            float: right;
        }

        .numDistance {
            text-align: right;
        }
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry">
    </script>
    <script>
        let watchId; 
        let map; 
        let poly; 
        let lastLatLng; 

        let conEarthMi = 3963.19;

        function initMap() {
            let btnStartWatch = document.getElementById('startWatch');
            let btnStopWatch = document.getElementById('stopWatch');
            btnStartWatch.addEventListener('click', startWatch, false);
            btnStopWatch.addEventListener('click', stopWatch, false);

            lastLatLng = new google.maps.LatLng(40.7141667, -74.0063889); // new york 
            let myOptions = {
                zoom: 14,
                center: lastLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(document.getElementById('mapCanvas'), myOptions);
            let polyOptions = {
                strokeColor: '#00FF00',
                strokeOpacity: 1.0,
                strokeWeight: 3
            }
            poly = new google.maps.Polyline(polyOptions);
            poly.setMap(map);
        }
        function successCallback(position) {
            let posLat = position.coords.latitude;
            let posLng = position.coords.longitude;
            let newLatLng = new google.maps.LatLng(posLat, posLng);

            let distFromLast = google.maps.geometry.spherical.computeDistanceBetween(newLatLng,
                lastLatLng, conEarthMi);

            if (distFromLast > 0.25) {
                let path = poly.getPath();
                path.push(newLatLng);
                let marker = new google.maps.Marker({
                    position: newLatLng,
                    title: '#' + path.getLength(),
                    map: map
                });
                map.setCenter(newLatLng);
                document.getElementById('myPosLat').innerHTML = posLat.toFixed(8);
                document.getElementById('myPosLng').innerHTML = posLng.toFixed(8);
                document.getElementById('watchStatus').innerHTML = 'Updated Position (#' + path.getLength() + ')';
                lastLatLng = newLatLng;

            }
        }
        function errorCallback(error) {
            let errMessage = 'ERROR: ';
            let divWatchStatus = document.getElementById('watchStatus');
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    errMessage += 'User did not share geolocation data.';
                    break;
                case error.POSITION_UNAVAILABLE:
                    errMessage += 'Could not detect current position.';
                    break;
                case error.TIMEOUT:
                    errMessage += 'Retrieving position timed out.';
                    break;
                default:
                    errMessage += 'Unknown error.';
                    break;
            }
            divWatchStatus.innerHTML = errMessage;
        }
        function startWatch() {
            let divWatchStatus = document.getElementById('watchStatus');
            if (navigator.geolocation) {
                if (watchId == null) {
                    let posOptions = {
                        maximumAge: 40000,
                        timeout: 20000,
                        enhancedAccuracy: true
                    }
                    watchId = navigator.geolocation.watchPosition(successCallback,
                        errorCallback,
                        posOptions);
                    divWatchStatus.innerHTML = 'Watching Location (' + watchId + ')';
                }
            } else {
                divWatchStatus.innerHTML = 'Geolocation Not Supported';
            }
        }
        function stopWatch() {
            if (watchId != null) {
                navigator.geolocation.clearWatch(watchId);
                watchId = null;
                document.getElementById('watchStatus').innerHTML = 'Off';
            }
        }
        window.addEventListener('load', initMap, false);
    </script>
</head>

<body>
    <div id="container">
        <div id="mapCanvas"></div>
        <div id="btnMap">
            <button id="startWatch">Start Watch</button>
            <br>
            <button id="stopWatch">Stop Watch</button>
        </div>
        <div id="location">
            <table id="status">
                <tr>
                    <td>Latitude:</td>
                    <td class="numDistance">
                        <div id="myPosLat"></div>
                    </td>
                </tr>
                <tr>
                    <td>Longitude:</td>
                    <td class="numDistance">
                        <div id="myPosLng"></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div id="watchStatus"></div>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</body>

</html>

Related Topic