Sunday, March 23, 2014

HTML5: Geolocation API

Note:
Currently Firefox 3.5, Chrome 5, Safari 5 and Opera 10.60 all have support for the geolocation API.

What is Geolocation API?
The geolocation API gives us a way to locate the exact position of our visitor.

How to use the API?
The geolocation API offers three methods for getting the geo information:
  • getCurrentPosition - user’s current location.
  • watchPosition - keeps polling at regular intervals to see if the location has changed.
  • clearPosition - Used with watchPosition. watchPosition returns a unique identifier that is passed in to clearWatch to clear that particular watch.
When using either of these methods, most devices will prompt the user and ask whether they want to share their location with the application.
Different browsers handle this in different ways.
Firefox does it via an alert box.


Input parameters to getCurrentPosition and watchPosition methods are:
  • Success handler
  • Error handler
  • Geolocation options
Success Handler
If the user permits the browser to share his geolocation the success handler is called.
The handler receives a Position object containing two properties: 
  • coords object (containing coordinate information) 
  • timestamp.

Using the coordinate data, you could easily map the user’s current position in Google Map.

Error Handler:
Notify the user in case of any error.

GeoLocation Options:
All the geolocation options are optional:

enableHighAccuracy (default false)
  • The enableHighAccuracy tells the device to try to get a more accurate reading on the latitude and longitude
timeout (in ms - default 0)
  • The timeout tells the geolocation lookup how long it should wait before giving up and triggering the error handler.
  • Setting a zero time out (the current default) tells the browser to never time out.
maximumAge (in ms - default 0)
  • Tell the browser whether to use recently cached position data.Setting the maximumAge to zero means the browser must look up a new position on each request.

Output:


Code Snippets:

Call to getCurrentPosition

 
 Update Location:

 
 Error handler: