Geolocation In HTML5

Understand term Geolocation

The Geolocation API of HTML5 helps identifying the user’s location. That can be used to provide location-specific information. For privacy reasons, the user is asked for permission to report location information. The HTML 5 geolocation API provides the geographical location of the user. There are many techniques used to identify the location of the user. A desktop browser generally uses WiFi or IP based positioning techniques whereas a mobile browser uses cell triangulation, GPS and A-GPS (Assistive GPS) to triangulate between mobile phone towers and public masts to determine the location and WiFi based positioning techniques, and so on.

The Geolocation API will use any of these techniques to identify the user’s location. The Geolocation API protects the user’s privacy by mandating that the user permission should be sought and obtained before sending the location information of the user to any website. So the user will be prompted with a popover or dialog requesting for the user’s permission to share the location information. The user can accept or deny the request.



Geolocation Object
 
The Geolocation API is published through the navigator.geolocation object. If this object is present then the geolocation service works.

var geolocation=navigator.geolocation;

The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device.

Browser Compatibility

The geolocation property of the global navigator object helps in detecting the browser support for the Geolocation API.

If (navigator.geolocation)
{
//Get the user’s current position
}
Else
{
Alert (‘Geolocation is not supported in your browser’);
}

Geolocation Methods

The getCurrentPosition method gets the current location of the user. It takes two arguments in the form of callbacks, one is the Success Callback function. This callback function is invoked only when the user accepts to share the location information and the location data is successfully fetched by the browser. The location data will be available as a position object. The success callback takes a Position object as an argument. It optionally takes a third argument in the form of a PositionOptions object. the second one is the Error Callback function for a failed location query.

Properties of Position object

Property Value Unit
Coords.latitude Double degrees
Coords.langitude Double degrees
Coords.altitude Double or null meters
Coords.accuracy Double meters
Coords.altitudeAccuracy Double or null meters
Coords.heading Double or null Degrees clockwise
Coords.speed Double or null Meters/second
timeStamp DOMTimeStamp Like the Date object

The coords object has the following properties:

  • Latitude, longitude: Geographic coordinates in decimal degrees
  • Accuracy: Accuracy level of the latitude and longitude coordinates in meters. Less accuracy when the number is big.
  • Altitude: Height of the position above the sea level in meters
  • AltitudeAccuracy: Denotes how far off the altitude position could be from the actual attitude value obtained in meters. The larger the number the lesser the accuracy.
  • Heading: Provides 360 degree heading information
  • Speed: Indicates relative speed in Meters Per Second.

Syntax of getCurrentPosition ( ) method

getCurrentPosition (showLocation, ErrorHandler, options);

Let define parameters of getCurrentPosition

showLocation: This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object that stores the returned location information.

ErrorHandler: This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the Position Error object that stores the returned error information.

Options: This optional parameter specifies a set of options for retrieving the location information. We can specify:

  • Accuracy of the returned location information
  • Timeout for retrieving the location information
  • Use of cached location information.

    Code

    <!DOCTYPE HTML>
    <head>
    <script type="text/JavaScript">
        function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
        }

        function errorHandler(err) {
            if (err.code == 1) {
                alert("Error: Access is denied!");
            } else if (err.code == 2) {
                alert("Error: Position is unavailable!");
            }
        }
        function getLocation() {

            if (navigator.geolocation) {

                var options = { timeout: 60000 };
                navigator.geolocation.getCurrentPosition(showLocation, errorHandler,
    options);
            }
            Else
            {
                alert("Geolocation is not supported by browser");
            }
        }
    </script>
    </head>
    <html>
    <body>
       <form>
         <input type="button" onclick="getLocation();" value="Get Location"/>
       </form>
    </body>
    </html>


    When you write, save and open this web page in your browser, it gives output like this;


watchPosition: This method retrieves your current location periodically. The location information is returned in a Position object. Each update returns a new Position object. The watchPosition method returns a unique transaction ID (number) associated with the asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving location updates.

Syntax

watchPosition(showLocation, ErrorHandler, options);

Code

<!DOCTYPE HTML>
<head>
<script type="text/JavaScript">
    var watchID;
    var geoLoc;
 
    function showLocation(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        alert("Latitude : " + latitude + " Longitude: " + longitude);
    }
 
    function errorHandler(err) {
        if (err.code == 1) {
            alert("Error: Access is denied!");
        } else if (err.code == 2) {
            alert("Error: Position is unavailable!");
        }
    }
    function getLocationUpdate() {
 
        if (navigator.geolocation) {
            var options = { timeout: 60000 };
            geoLoc = navigator.geolocation;
            watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
        } else {
            alert("Geolocation is not supported by browser!");
        }
    }
</script>
</head>
<html>
<body>
   <form>
     <input type="button" onclick="getLocationUpdate();"value="Watch Update"/>
   </form>
</body>
</html>



clearWatch( ): The clearWatch method cancels an ongoing watchPosition call. When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device. The clearWatch method does not return a value.

Syntax: clearWatch(watchId);

Parameters used:

watchID:: This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call.

Code

<!DOCTYPE HTML>
<head>
<script type="text/javascript">
    var watchID;
    var geoLoc;
    function showLocation(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        alert("Latitude : " + latitude + " Longitude: " + longitude);
    }
 
    function errorHandler(err) {
        if (err.code == 1) {
            alert("Error: Access is denied!");
        } else if (err.code == 2) {
            alert("Error: Position is unavailable!");
        }
    }
    function getLocationUpdate() {
 
        if (navigator.geolocation) {
            // timeout at 60000 milliseconds (60 seconds)
            var options = { timeout: 60000 };
            geoLoc = navigator.geolocation;
            watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
        } else {
            alert("Geolocation is not supported by your browser!");
        }
    }
    function stopWatch() {
        geoLoc.clearWatch(watchID);
    }
</script>
</head>
<html>
<body>
   <form>
     <input type="button" onclick="getLocationUpdate();" 
                             value="Watch Update"/>
     <input type="button" onclick="stopWatch();" 
                             value="Stop Watch"/>
   </form>
</body>
</html>

 



Error Callback Function ( )

The optional callback function that takes a "PositionError" object as its input parameter. This function is invoked when any error has occurred. In the request timeout case, the user has declined to share the location information, and when the location information is unavailable.

Position Options

Options available when the user retrieves the information.

  • enableHighAccuracy: Boolean. If true, the user agent will try to provide the most accurate position. This can result in a slower response time and higher power consumption. If false then a less accurate position will be obtained. The default value is false.
  • Timeout: Positive long value. It denotes the maximum time (in milliseconds) that the user agent can take to respond with the location data. The default value is Infinity.
  • maximumAge: Positive long value. It denotes how long (in milliseconds) the user agent can keep using the cached location data before trying to obtain new location data. A zero value indicates that the user agent must not use the cached location data and the infinity value indicates that the cached location data must be used by the user agent.

Use Google Maps

To plot our location on Google Maps we use the Google Maps API. The following explains all points step-by-step.

  1. Convert the latitude and longitude coordinates of the position object obtained using the Geolocation API into a Google maps latLng object.

    var googlePos = new google.maps.LatLng(position.coords.latitude,
    position.coords.longitude);

  2. Create a Map object specifying the map display options and the HTML div container where the map should be displayed. In the example we define the following three map options:

    • Zoom: Specifies the zoom level
    • Center: Specifies that the map should be centered at the user location
    • mapTypeId: Can be Roadmap, Satellite or Hybrid

    var mapOptions = {
                    zoom : 12,
                    center : googlePos,
                    mapTypeId : google.maps.MapTypeId.ROADMAP
                        };
        var mapObj = document.getElementById('mapTxt');
        var googleMap = new google.maps.Map(mapObj, mapOptions);

  3. Now we create a marker at the location as in the following:

    var markerOpt = {
            map : googleMap,
            position : googlePos,
            title : 'Hi , I am here',
            animation : google.maps.Animation.DROP
            };
        var googleMarker = new google.maps.Marker(markerOpt);


    The Code marker options indicate the following three important points:

    • Map: Map object where the marker should appear
    • Position: latlng position at which the marker should be displayed
    • Title: Title that should appear when we hover on the marker
     
  4. Find the address of your location using the reverse geocoding API and show the address obtained when you click on the marker.

    var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            'latLng' : googlePos
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                var popOpts = {
                content : results[1].formatted_address,
                position : googlePos
                };
            var popup = new google.maps.InfoWindow(popOpts);
                                    google.maps.event.addListener(googleMarker, 'click', function() {
                                    popup.open(googleMap);
                            });
                } else {
                    alert('No results found');
            }
            } else {
                alert('Geocoder failed due to: ' + status);
            }
    });


    Now for the entire sample code:

    <!DOCTYPE html>
    <html>
    <head>
    <title>Sample Map</title>
    <style>
    #mapdiv {
        margin: 0;
        padding: 0;
        width: 500px;
        height: 500px;
    }
    </style>
     
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
    <script>
        var watchId = null;
        function geoloc() {
            if (navigator.geolocation) {
                var optn = {
                    enableHighAccuracy: true,
                    timeout: Infinity,
                    maximumAge: 0
                };
                watchId = navigator.geolocation.watchPosition(showPosition, showError, optn);
            } else {
                alert('Geolocation is not supported in your browser');
            }
        }
     
        function showPosition(position) {
            var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var mapOptions = {
                zoom: 12,
                center: googlePos,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var mapObj = document.getElementById('mapdiv');
            var googleMap = new google.maps.Map(mapObj, mapOptions);
            var markerOpt = {
                map: googleMap,
                position: googlePos,
                title: 'Hi , I am here',
                animation: google.maps.Animation.DROP
            };
            var googleMarker = new google.maps.Marker(markerOpt);
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
                'latLng': googlePos
            }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        var popOpts = {
                            content: results[1].formatted_address,
                            position: googlePos
                        };
                        var popup = new google.maps.InfoWindow(popOpts);
                        google.maps.event.addListener(googleMarker, 'click', function () {
                            popup.open(googleMap);
                        });
                    } else {
                        alert('No results found');
                    }
                } else {
                    alert('Geocoder failed due to: ' + status);
                }
            });
        }
     
        function stopWatch() {
            if (watchId) {
                navigator.geolocation.clearWatch(watchId);
                watchId = null;
     
            }
        }
     
        function showError(error) {
            var err = document.getElementById('mapdiv');
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    err.innerHTML = "User denied the request for Geolocation."
                    break;
                case error.POSITION_UNAVAILABLE:
                    err.innerHTML = "Location information is unavailable."
                    break;
                case error.TIMEOUT:
                    err.innerHTML = "The request to get user location timed out."
                    break;
                case error.UNKNOWN_ERROR:
                    err.innerHTML = "An unknown error occurred."
                    break;
            }
        }
            </script>
     
        </head>
        <body onload="geoloc()">
            <p id = 'mapdiv'></p>
            <button onclick="stopWatch()">
                Stop
            </button>
        </body>
    </html>

    Result

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now