HTML5 Recipes: Geolocation

Location Based Applications have garnered a lot of attention in recent times. Suddenly everyone wants to know where you are, so that they can serve you data that is relevant to the context i.e. where you are. Location Based Applications/Services come in different varieties. Some of them a pure checkin type applications where you update where you are. Some other applications can return you specific data like restaurants or even weather data, depending on your location. There are interesting advances even made in geo-fencing, where notifications are sent as you move in or out of a defined region.

In summary, Location is here to stay and the ability of an application to know the users location is key. Several mechanisms exist today to determine the location of the users. In typically web based applications, the users network infrastructure / IP Address was deciphered and then a server side solution determined the location of the user. With advances in mobile devices, a GPS receiver on the device is common now and it could give an even finer location rather than a coarse location co-ordinate.

HTML5 has support for determining the location of the user via the Geolocation API. It supports both a one time location retrieval and also continuous location retrieval depending on the need of your application. Geolocation support is determined via the navigator.geolocation object in the browser. HTML5 Geolocation support is good in most Webkit based SmartPhone browsers.

Enough of theory. Let us see use the HTML5 Geolocation API to retrieve the location of the user right in the browser. We shall take a look at the getCurrentPosition() method available in the navigator.geolocation object. The getCurrentPosition method takes 3 parameters: the success callback function, error callback function and Position options object that we can specify. Both the error callback and options object are optional but they are good to have. Let us take a look at the code below:

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML GeoLocation Test</title>
<script type="text/javascript">

function findMyCurrentLocation(){
	var geoService = navigator.geolocation;
	if (geoService) {
		alert("Your Browser supports GeoLocation");
		navigator.geolocation.getCurrentPosition(showCurrentLocation,errorHandler,{enableHighAccuracy: true});
	} else {
		alert("Your Browser does not support GeoLocation.");

function showCurrentLocation(position){
	document.getElementById("mycurrentlocation").innerHTML = "Your location details --> Current Latitude : " + position.coords.latitude + " , Longitude : " + position.coords.longitude;

function errorHandler(error){
	  alert("Error while retrieving current position. Error code: " + error.code + ",Message: " + error.message);
<div id="main">
	<div id="mycurrentlocation"></div>
	<input type="button" value="Find My Location" onclick="findMyCurrentLocation()"/>

Let us break the code down now:

  • We have defined a button “Find My Location” and when we click it, the findMyCurrentLocation() method is invoked.
  • In the findMyCurrentLocation() method, we first determine if the browser support the HTML5 Geolocation API, by inspecting the navigator.geolocation object. If there is no support, we simply come out with an alert. If there is support present, we invoke the getCurrentPosition method. Notice that we have provided it 3 parameters. The first parameter is the success callback function. This function will be invoked when the browser is able to determine the location. The second parameter is the error callback method. This method will be invoked when the browser is unable to determine the location. The final i.e. 3rd parameter is a PositionsOptions object, where we specify extra criteria to help guide the Geolocation API for the kind of location data characteristics. In this example, we are specify an attribute enableHighAccuracy, which tells the browser to use the highest possible accuracy. Other attributes that you could specify are timeout and maxAge. Refer to the specification for more detail.
  • If the browser is able to determine the location, the success callback method is invoked. In our case, it is the showCurrentLocation method. A parameter of type Position is passed into this success callback method. The Position object has an attribute coords of type Coordinates that contains all the information about the Location that you want. We extract out the latitude and longitude as shown in the code. In addition to them, you can also extract out other attributes like altitude, speed, heading, etc.
  • If your location could not be determined, the error callback method is invoked. A parameter of type PositionError is passed to it. You can use this PositionError method to determine the exact reason why it failed via the code and message attributes. Do note that the code values could be among PositionError.PERMISSION_DENIED, PositionError.UNAVAILABLE and PositionError.TIMEOUT. So if you need to do some custom handling or error message depending on the error, you can check the value and then give a custom message instead of the message attribute because different browsers populate the PositionError.message attribute differently.

Note: Determining the Location of the user is a sensitive topic and brings up issues of privacy. The recommended practice is always of asking the user for permission, also known an opt-in. HTML5 Geolocation specification makes it clear that browsers need to ask the user for permission before determining the location. Each browser does this differently via a bar that typically appears just under the address bar. If you say “Yes” to the browser asking for permission, then it goes about its work to determine the location. if you refuse permission, then the error callback method will be invoked and the PositionError object will have PERMISSION_DENIED as the code value. Once you give the browser permission, it will remember that option on subsequent location determination. You can always go into the browser settings and clear this setting. So depending on whether you want to try this code out in your desktop browser or mobile browser, learn about the location settings and do set them, else the code will fail to determine your location due to lack of permission.

See it in action here.

In this recipe, we have covered the getCurrentPosition method that is a one time call to determine the location of the user. Some applications require to know the location of the user as it changes. There is another method called watchPosition, which we shall cover in brief in the next recipe along with how to integrate location and display a Google Map.

HTML5 Geolocation Recipes

  1. Getting Started with Geolocation
  2. More on Geolocation

Back to HTML5 Series


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s