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:
W3C Geolocation spec states: No guarantee is given that the API returns the device’s actual location.
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:
The success callback is passed a position object that contains a coordinates object and a timestamp.
--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.
getCurrentPosition
watchPosition
clearWatch
Method | Description |
---|---|
getCurrentPosition | a one-shot method for grabbing the user’s current location. |
watchPosition | Returns 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. |
clearWatch | This 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.
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:
navigator.geolocation.getCurrentPosition(function (position) { alert('We found you!'); // now do something with the position data });
The success callback is passed a position object that contains a 'coordinates' object and a 'timestamp'.
The coordinates object contains the following:
Properties | Description |
---|---|
latitude | which is specified in decimal degrees. |
longitude | which is specified in decimal degrees. |
accuracy | which is specified in meters. |
altitude | which is specified in meters above the ellipsoid. |
altitudeAccuracy | which is specified in meters. |
heading | which is direction of travel specified in degrees |
speed | which 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.
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:
/* 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 }
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:
The code property will be only one of the following:
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+).
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 "); }); }
The third argument to both getCurrentPosition
and watchPosition
are the geolocation options which are optional.
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):
navigator.geolocation.getCurrentPosition(success, error, { enableHighAccuracy: true, timeout: 2000, maximumAge: 0 });
Properties | Description |
---|---|
enableHighAccuracy | The 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. |
timeout | The 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. |
maximumAge | maximumAge 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. |