Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

HTML5 is making geolocation much, much easier to do. It is now a standard API and it’s pretty easy to do.

    The Geolocation API is supported by the following browser versions and up:

  • Chrome 5.0
  • Firefox 3.5
  • Android 2.0
  • Iphone 3.0
  • IE 9.0+
  • Safari 5.0
  • Opera 10.6

The basic functionality to get the user’s current geolocation is accessed by:

<script>
     navigator.geolocation.getCurrentPosition(success, error, positionOptions);
</script>

The error handler and the options are optional. My signature is as follows:

<script>
     navigator.geolocation.getCurrentPosition(
          handleGeolocationSuccess,
          handleGeolocationError,
          positionOptions
);
</script>

It is also possible watch a user’s position. If you watch a user’s position, then you don’t have to poll it. The browser will notify you when the user’s location changes.

This is how the watch functionality is accessed:

<script>
     var id = navigator.geolocation.watchPosition(success, error, positionOptions);
</script>

The id is needed to stop the watch functionality.

<script>
     navigator.geolocation.clearWatch(id);
</script>

The positionOptions object is used to specify options to the geolocation API. The definition of the positionOptions object is as follows:

  • enableHighAccuracy – boolean. Require high accuracy (e.g. GPS).
  • timeout – milliseconds. How long should the code wait till it determines that it can’t get a location
  • maximumAge – the maximum age of a previous location that can be used. Use the last position that the browser has as long as that position is less than N milliseconds old. Set to 0 to require the current position immediately.

An example of the positions object is:

{enableHighAccuracy: true, timeout: 5000, maximumAge: 60000}

The full example is below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Java Ninja Geolocation prototype</title>
</head>
<body>
    <button onclick="getCurrentGeolocation()">Locate Me!!!</button>
    <button onclick="watchGeolocation()">Watch Me!!!</button>
    <button id="stopWatchingGeolocation" style="display: none" onclick="stopWatchingGeolocation()">
        Stop watching Me!!!
    </button>

    <script>
        /** Variable to make seconds more readable. */
        var seconds = 1000;  // 1000 milliseconds = 1 second

        /** Positions Object to contain all of the settings that we want for the geolocation.getCurrentPosition call. */
        var positionOptions = {
            /** require high accuracy (e.g. GPS). */
            enableHighAccuracy: true,
            timeout: 5 * seconds,
            /**
             * Use a position that is up to a minute old.
             * Set to 0 to ask for the current position right now.  Makes it faster and less expensive for the user if
             * they are getting repeated requests.
             */
            maximumAge: 60 * seconds
        };

        /** The geolocation watch id.  This is used to stop the watch. */
        var watchGeolocationId = 0;

        /**
         * Get the user's current geolocation.
         */
        function getCurrentGeolocation() {
            navigator.geolocation.getCurrentPosition(
                    handleGeolocationSuccess,
                    handleGeolocationError,
                    positionOptions
            );
        }

        /**
         * Watch the user's geolocation.
         */
        function watchGeolocation() {
            watchGeolocationId = navigator.geolocation.watchPosition(
                    handleGeolocationSuccess,
                    handleGeolocationError,
                    {enableHighAccuracy: true, timeout: Infinity, maximumAge: 0}
            );
            // Used old school so the example wouldn't have to pull in Jquery
            document.getElementById("stopWatchingGeolocation").style.display = "block";
        }

        /**
         * Stop watching the user's geolocation.
         */
        function stopWatchingGeolocation() {
            navigator.geolocation.clearWatch(watchGeolocationId);
            // Used old school so the example wouldn't have to pull in Jquery
            document.getElementById("stopWatchingGeolocation").style.display = "none";
        }

        /*
         * Geolocation handler functions
         */


        /**
         * Success handler for geolocation.getCurrentPosition.
         * @param position
         */
        function handleGeolocationSuccess(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var accuracy = position.coords.accuracy;

            alert('latitude=' + latitude + "\nlongitude=" + longitude + "\naccuracy=" + accuracy + " meters");
        }

        /**
         * Error handler for geolocation.getCurrentPosition.
         * @param err
         */
        function handleGeolocationError(err) {
            if (err.code == 1) {
                alert('PERMISSION_DENIED - User declined to provide geolocation data');
            } else if (err.code == 2) {
                alert('POSITION_UNAVAILABLE - Network is down or GPS satellites are unavailable')
            } else if (err.code == 3) {
                alert('TIMEOUT - Unable to determine location within the allotted time')
            }
        }
    </script>
</body>
</html>

July 9th, 2015

Posted In: Geolocation, HTML, HTML5

Tags: , ,

Leave a Comment

LinkedIn Auto Publish Powered By : XYZScripts.com