Html 5 Geolocation

About Geolocation

The HTML5 specification includes a new Geolocation API, which allows for scripted access to geographical location information associated with the a device's browser.

Visitor's location may be determined by any of the following:

  • IP address
  • wireless network connection
  • cell tower
  • GPS hardware on the device

W3C Geolocation spec states: No guarantee is given that the API returns the device’s actual location.

Checking for Support with User's browser

Before we attempt to use geolocation for determining the location of the Internet device, we should ensure that our visitor’s browser supports the GeoLocation feature natively. If it does, call the getCurrentPosition method:

if (navigator && navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(geo_success, geo_error);
} else {
    error('GeoLocation is not supported.');
}

Since this method executes asynchronously, pass it two callback functions: geo_success and geo_error. The error callback is passed a position error object that contains a code and a message property. The code can be one of the following:

  • 0 - Unknown
  • 1 - Permission Denied
  • 2 - Position Unavailable
  • 3 - Timeout

The success callback is passed a position object that contains a coordinates object and a timestamp.

--

Geolocation API Methods

The geolocation API exists inside the navigator object and contains only three methods to determine the user’s current position and also get notified of changes to their position.

  1. getCurrentPosition
  2. watchPosition
  3. clearWatch
MethodDescription
getCurrentPositiona one-shot method for grabbing the user’s current location.
watchPositionReturns the user’s current location but continues to monitor their position and keeps polling at regular intervals to see if their location has changed and invoke the appropriate callback every time the position changes.
clearWatchThis method ends the watchPosition method's monitoring of the current position.

The watchPosition and clearWatch are paired methods. watchPosition returns a unique identifier that is passed in to clearWatch to clear that particular watch.

--

Retrieving the Current Position

The current position is retrieved using the getCurrentPosition API method which takes three arguments.

void getCurrentPosition(successCallback, errorCallback, options); 

getCurrentPosition and watchPosition mirror each other and take the same arguments:

  • successCallback - success handler
  • errorCallback - error handler
  • options - geolocation options
snippet
navigator.geolocation.getCurrentPosition(function (position) {
alert('We found you!');
// now do something with the position data
});
Success Callback

The success callback is passed a position object that contains a 'coordinates' object and a 'timestamp'.

The coordinates object contains the following:

PropertiesDescription
latitudewhich is specified in decimal degrees.
longitudewhich is specified in decimal degrees.
accuracywhich is specified in meters.
altitudewhich is specified in meters above the ellipsoid.
altitudeAccuracywhich is specified in meters.
headingwhich is direction of travel specified in degrees
speedwhich is specified in meters per second.

Of those 7, only 3 are guaranteed to be there: latitude, longitude, and accuracy. The heading and speed attributes are only relevant if we're tracking the user across multiple positions.

Grabbing the Latitude and Longitude:-

To get the latitude and longitude use the following code.

snippet
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var coords = position.coords;
        showMap(coords.latitude, coords.longitude,
            coords.accuracy);
    });
}

Our successCallback is set to the function displayOnMap. Here's what this function looks like:

snippet
/* todo-clari 
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayOnMap);
}*/
function displayOnMap(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    // Let's use Google Maps to display the location
}
Error Callback

The second argument to the getCurrentPosition and watchPosition method is the error handler.

If you want to notify the user of any errors in getting the position use the error handler callback. The error handler may trigger if the user denies their their location.

The error handler receives a single argument containing a position error object containing two properties:

  1. (i) code
  2. (ii) message

The code property will be only one of the following:

  • PERMISSION_DENIED (numeric value 1)
  • POSITION_UNAVAILABLE (numeric value 2)
  • TIMEOUT (numeric value 3)

The message property is useful for developing and debugging but wouldn't be appropriate to show the user. The message property isn't always available (as it's not currently in Firefox 3.6+).

snippet
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function(position) {
            var coords = position.coords;
            showMap(coords.latitude, coords.longitude, coords.accuracy);
        },
        function(error) {
            var errorTypes = {
                1: 'Permission denied',
                2: 'Position is not available',
                3: 'Request timeout'
            };
            alert(errorTypes[error.code] + ": means we can't
                determine your position ");
            });
    }
Options - Configuring the geolocation

The third argument to both getCurrentPosition and watchPosition are the geolocation options which are optional.

  • enableHighAccuracy (Boolean, default false)
  • timeout (in milliseconds, default infinity/0)
  • maximumAge (in milliseconds, default 0)

For example, to request high accuracy, a two-second timeout, and to never use old geo data, call getCurrentPosition using the following options (where success and error are predefined functions):

snippet
navigator.geolocation.getCurrentPosition(success, error, {
    enableHighAccuracy: true,
    timeout: 2000,
    maximumAge: 0
});
PropertiesDescription
enableHighAccuracyThe tells the device to try to get a more accurate reading on the latitude and longitude. By default enableHighAccuracy is set to false. On a mobile device, this may be to make use of the GPS on a phone, which could consume more power on the mobile device.
timeoutThe timeout tells the geolocation lookup how long it should wait before giving up and triggering the error handler (but won't start counting down if it's waiting for the user to approve the request). If it does timeout, the error code is set to 3 (TIMEOUT). Setting a zero time out (the current default) tells the browser to never time out.
maximumAgemaximumAge can be used to tell the browser whether to use recently cached position data. If there is a request that is within the maximumAge (in milliseconds), it is returned instead of requesting a new position. maximumAge can also be Infinity, which tells the browser to always use a cached position. Setting the maximumAge to zero (the default value) means the browser must look up a new position on each request.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +