HTML5 Geolocation


Definition of the Geolocation API in the specification: "The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude." (technically the Geolocation API is not a part of the HTML5 standard, instead, it's actually a separate specification)
The location information may be sourced from various points - such as Wifi, IP, GPS, GSM/CDMA cell IDs, etc. 
The location information can then be used to further provide meaningful utility to the user - such as getting directions, information on business or surrounding area. 
The Geolocation API requires the user's permission. Location information is sensitive and the API needs to have the user's consent.  This action could be taken up by the browser in various forms - such as a question in the browser's information bar or a pop-up dialog. The user may be offered the choice to remember his/her response from that point onwards.
As with other HTML5 features, you need to verify the support for the API in the client browser. This can be done simply by testing for the existence of the geolocation object.

API Methods

  1. getCurrentPosition
         The getCurrentPosition method is used for a one time query on the location. 
  1. watchPosition 
         The watchPosition method is used when location updates are also needed. When you want to stop the continued updates for the position, you need to call the clear watch method, using the same watchID value. This is very useful when you want to track changes such as direction mapping applications.
Both methods are asynchronous. The methods specify a mandatory successCallback argument and can optionally specify an errorCallback function and options for the location query.  The various options that can be customized for the location query are: enableHighAccuracy (precise location but may cause slower response and higher power usage), timeout (default of zero which indicates no timeout) and maximumAge (expiration for cached location). 
In case there was an error, the error callback is invoked if it was specified in the getCurrentPosition/watchPosition method call. Typical error situations are if the user has denied permission to access the location information, or the position is unavailable, timeouts, etc.
If the location was successfully retrieved, the success callback method is invoked. Once you get the location, you can utilize it in your application. 
The result location information is returned in a Position object. The Position object has properties which can include expanded location information. Latitude, longitude, altitude, accuracy, altitude accuracy, heading, speed, and timestamp. The Latitude, longitude and accuracy properties are populated whereas the remaining properties may be populated if supported or may be null.

Code Sample

In this code sample, we will run a very basic script to get the user's location and display the latitude and longitude in a text box.  When the "Get my Location" button is clicked, we check if the geolocation API is supported and if it is supported, a call is made to the getCurrentPosition method of the navigator object. The success callback method (displayResult) displays the latitude and longitude retrieved for the user or in case an error occurred, the error callback gets executed and the error message is displayed to the user. 
Sample in Action: Here are some screenshots of the application running in Mozilla Firefox 6.0.2
Figure: browser prompt for user's permission 
Figure: Success - got the location! 
Figure: Error 
Source Code: 
save as geo.htm (or a file name of your preference)
  1. <!DOCTYPE HTML>  
  2. <html>  
  3.    <body> 
  4.         <script language="javascript">  
  5.       function getUserLoc() {  
  6.          if (navigator.geolocation) {  
  7.            navigator.geolocation.getCurrentPosition(  
  8. displayResult,  
  9. displayError);  
  10.          }  
  11.          else {  
  12.              setMessage("Geolocation is not supported by this browser");  
  13.          }  
  14.      }  
  15.     function displayResult(position) {  
  16.         setMessage("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);  
  17.     }  
  18.     function setMessage(msg) {  
  19.         document.forms[0].myLoc.value = msg;  
  20.     }  
  21.     function displayError(error) {  
  22.         var errors = { 1: 'Permission denied', 2: 'Position unavailable', 3: 'Request timeout' };  
  23.         setMessage("Error occured: " + errors[error.code]);  
  24.     }   
  25. </script>  
  26.         <form>  
  27.             <input type="button" onClick="getUserLoc( );" value="Get my location"/>  
  28.             <input type="label" name="myLoc" size="200"/>  
  29.         </form> 
  30.     </body>  
  31. </html>  


In this article, we took a look at the geolocation API. It's a simplistic solution but opens up a universe of possibilities. An application could tie in with a library such as the Google map APIs to provide elaborate geography/mapping solutions. 
Happy Coding!