barbarian meets coding

WebDev, UX & a Pinch of Fantasy

HTML5 Geolocation API

This article is part of my personal wiki where I write personal notes while I am learning new technologies. You are welcome to use it for your own learning!

HTML5 provides a new geolocation api that allows the user to provide his/her location to web applications. The api entry point is the navigator.geolocation object.

This object has three methods:

  • getCurrentPosition: get the user current position
  • watchPosition: allows you to specify an event handler for whenever the user position changes
  • clearWatch: removes an event handler from following the user’s position

To get the user’s position you can use the getCurrentPosition method as depicted below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// getCurrentPosition(success, error, options)

var options = {
    enableHighAccuracy: true,
    timeout: 2000,
    maximumAge: 0 // caching configuration, 0 means no caching
}

if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition(/* success */function(position){
       var coords = position.coords;
       console.log("Your position is: ", coords.latitute, coords.longitude, " with more or less ", coords.accuracy, " meters accuracy." );
    }, /* error */ function(e){
        console.error("there was an error!! ", e);
    }, options);

}

You can use the watchPosition to register an event handler for every time the user position changes:

1
2
3
4
5
6
7
8
9
// watchPosition(success, error, options) (same as getCurrentPosition)

var handlerId = navigator.geolocation.watchPosition(function(pos){
    // do something with position
})

if (iGetTired){
    navigator.geolocation.clearWatch(handlerId);
}

The Position object returned by the geolocation api has the following properties:

  • coords
    • latitute
    • longitude
    • altitude
    • accuracy
    • altitudeAccuracy
    • heading
    • speed
  • timestamp

Comments