Adds

HTML5 Geolocation API – A Complete Tutorial

With HTML5 Geolocation API you can now share your location with different web sites.

In many cases, obtaining user location would be extremely useful for better user experience, for example:

  • News sites can provide localized headlines and weather report.
  • E-commerce sites can provide estimated shipping cost and inform product availability in visitors area.
  • Movie websites can immediately provide movies playing in nearby theatres.
  • Movie websites can immediately provide movies playing in nearby theatres.
  • Restaurant finder website can provide you details of restaurants located near to your current location.

The Geolocation API

The geolocation API allows you to easily fetch the geographical position of a user. If the browser support Geolocation API, one can easily get the Longitude and Latitude by just using Javascript.

There are many techniques used to identify the location of the user. A desktop browser generally uses WIFI or IP based positioning techniques whereas a mobile browser uses cell triangulation, GPS, A-GPS, WIFI based positioning techniques, etc. The Geolocation API will use any one of these techniques to identify the user’s location.

As this API will display current location of the visitor it can potentially become a privacy problem, which is why this API will only work with the permission of the visitor.


Geolocation API Browser Compatibility

Geolocation functionality is supported in following browsers

  • Google Chrome
  • Internet Explorer 9 and higher
  • Firefox 3.5 and higher
  • Opera 10.6 and higher
  • Safari 5

Implementing the Geolocation API

Steps to implement Geolocation is mentioned below.


1 . Check Browser compatibility

Before getting the visitors location it is important to check if the visitors browser will support the Geolocation API or not. If it doesn't support the Geolocation API then it will error when trying to get the location.

Use the following Javascript code to check visitor browser supports to Geolocation API.

if (navigator.geolocation) {
 // Get the user's current position
} else {
  error('Geolocation is not supported in your browser');
}

Get Visitors Current Position

To get the visitors current location you need to use the navigator object, from here you can access the geolocation API to call the method getCurrentPosition method. This accepts three parameters:

  • Success callback function
  • Error callback function
  • Position options

If the location data is fetched successfully, the success callback function will be invoked with the obtained position object as its input parameter. Otherwise, the error callback function will be invoked with the error object as its input parameter.

Geolocation APIs can be accessed via the geolocation object, which is a service object that allows widgets to retrieve information about the geographic location of the device.

var geolocation = navigator.geolocation;

To get the user current location we need to use the getCurrentPosition() method:

function getCurrentLocation() {
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosition(showCurrentLocation, showError, optn);
}

In the above example showCurrentLocation is success callback methods, showError is error callback method and optn is Position Options. Description of all these methods is given below.


1 . Success callback function

Success callback function will invoked only when the user accepts to share the location information and the location data is successfully fetched by the browser. The location data will be available as a position object and the function will be called with the position object as its input parameter. position object contains timestamp property denotes the time at which the location data is retrieved and a coords object.

coords object contains the geographic location of the device, along with information about heading and speed etc. The coords object has the following properties

  • coords.latitude : represents the latitude in decimal degrees [-90.00, +90.00] range.
  • coords.longitude: represents the latitude in decimal degrees [180.00, +180.00] range.
  • coords.altitude : represents the altitude in meters.
  • coords.accuracy : represents the accuracy of the latitude and longitude in meters
  • coords.altitudeAccuracy: specifies the accuracy of the altitude in meters
  • coords.heading: determines the current direction of movement of the device. The counting is in degrees clockwise relative to true north

  • timestamp: the time when the location information was retrieved
  • coords.speed: determines the device's current ground speed in meters per second

2. Error callback function

This is an optional callback function that takes a ‘Position Error’ object as its input parameter. This function is invoked under any one of the following scenario.

  • User has denied to share the location information
  • Location information is not available
  • Unknown Error occurred
  • Request Timeout

error object has following error code.

  • PERMISSION_DENIED
  • POSITION_UNAVAILABLE
  • UNKNOWN_ERROR
  • TIMEOUT

Sample javaScript code for error callback function is given below.

function showError(error)
    {
      switch(error.code) 
        {
        case error.PERMISSION_DENIED:
			alert("User denied the request for Geolocation.");
			break;
		case error.POSITION_UNAVAILABLE:
			alert("Location information is unavailable.");
			break;
		case error.TIMEOUT:
			alert("The request to get user location timed out.");
			break;
		case error.UNKNOWN_ERROR:
			alert("An unknown error occurred.");
			break;
        }
    }

3. Position Options

This optional parameter specifies a set of options for retrieving the location information. You can specify Accuracy of the returned location information ,Timeout for retrieving the location information and Use of cached location information . Detail description is given below.

  • enableHighAccuracy : This must be a boolean value.If this value is provided as true, the user agent will provide the most accurate position.
  • Timeout: It denotes the maximum time (in milliseconds) that the user agent can take to respond with the location data.
  • maximumAge : It denotes how long (in milliseconds) the user agent can keep using the cached location data before trying to obtain new location data. A zero value indicates that the user agent must not use the cached location data and infinity value indicates that the cached location data must be used by the user agent.

javaScript code for position option is given below.

if (navigator.geolocation) {
var optn = {
			enableHighAccuracy : true,
			timeout : Infinity,
			maximumAge : 0
		};
					 navigator.geolocation.getCurrentPosition(showCurrentLocation , showError, optn);
} else {
		alert('Geolocation is not supported in your browser');
}

Tracking of Location changes(Get Current Location Repeatedly )

The method watchPosition() is used to watch users location. Below is the syntax for this method:

long navigator.geolocation.watchPosition(callback);

This method takes one argument, the callback function which gets called when location is obtained. Unlike getCurrentPosition() method, the watchPosition() method returns a long value watchID. This id can be used to uniquely identify the requested position watcher; and this value can be used in tandem with the clearPosition() method to stop watching the user’s location.

The main difference between getCurrentPosition and watchPosition is that watchPosition keeps informing your code should the position change, so basically it keeps updating the user’s position. This is very useful if they’re on the move and you want to keep track of their position, whereas getCurrentPosition is a once off. This method also returns a watchID which is required when you want to stop the position constantly being updated by calling clearWatch method is called.

navigator.geolocation.clearWatch(watchID);

Sample javaScript code is given below.

function startWatch(){
if (navigator.geolocation) {
	var optn = {
		enableHighAccuracy : true,
		timeout : Infinity,
		maximumAge : 0
	};
	watchId = navigator.geolocation.watchPosition(showPosition, showError, optn);
} else {
	alert('Geolocation is not supported in your browser');
}
}
function stopWatch() {
.	if (watchId) {
		navigator.geolocation.clearWatch(watchId);
		watchId = null;
	}
}

Geolocation API and Google Maps integration

The Geolocation API is easy to use, it gives you a way to detect where you are, but it doesn’t provide any tools to see your location. We need a third-party tool like Google Maps to display our current location on the map.

Basically we will create a Google Maps object and then pass our location coordinates using map options.The following code now displays the location on a google Map.

First we need to convert the latitude and longitude coordinates of the position object obtained using the Geolocation API into a Google maps latLng object.

var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

Create a Map object specifying the map display options and the HTML div container where the map should be displayed. In the example below three map display options are specified.

  • Zoom : Specifies the zoom level.
  • Center: Specifies that the map should be centered at the user location
  • mapTypeId : Can be Roadmap, Satellite or Hybrid

Sample code is given below.

var mapProperty = {
				zoom : 11,
				center : googlePos,
				mapTypeId : google.maps.MapTypeId.ROADMAP
      				};
	var mapObj = document.getElementById('mapdiv');
	var googleMap = new google.maps.Map(mapObj, mapProperty);

Adding a Marker on your Location

It would be more useful if we could see exactly where we are located on the map. If you’ve previously used Google Maps, then you must be familiar with the markers(pins) used to mark the location. It looks like a pin which will exactly display your current location.

javaScript code to add marker at user's current location is given below.

var markerOption = {
		map : googleMap,
		position : googlePos,
		title : 'You are here',
		animation : google.maps.Animation.DROP
		};
	var googleMarker = new google.maps.Marker(markerOpt);

In the above code marker options indicates the following properties.

  • Map : Specifies the Map object where the marker should appear.
  • Position: Specifies the latlng position at which the marker should be displayed
  • Title : Title will appear when we hover on the marker

Putting All together to display user’s location

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of Showing Location on Google Map</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function showPosition(){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showMap, showError);
    } else{
        alert("Sorry, your browser does not support HTML5 geolocation.");
    }
}
 
// Define callback function for successful attempt
function showMap(position){
    // Get location data
    lat = position.coords.latitude;
    long = position.coords.longitude;
    var latlong = new google.maps.LatLng(lat, long);
    
    var myOptions = {
        center: latlong,
        zoom: 16,
        mapTypeControl: true,
        navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL}
    }
    
    var map = new google.maps.Map(document.getElementById("embedMap"), myOptions);
    var marker = new google.maps.Marker({position:latlong, map:map, title:"You are here!"});
}
 
// Define callback function for failed attempt
function showError(error){

   var err = document.getElementById('embedMap');
		switch(error.code) {
		case error.PERMISSION_DENIED:
		err.innerHTML = "User denied the request for Geolocation."
		break;
		case error.POSITION_UNAVAILABLE:
		err.innerHTML = "Location information is unavailable."
		break;
		case error.TIMEOUT:
		err.innerHTML = "The request to get user location timed out."
		break;
		case error.UNKNOWN_ERROR:
		err.innerHTML = "An unknown error occurred."
		break;
    
}
}
</script>
</head>
<body>
    <button type="button" onclick="showPosition();">Show My Position on Google Map</button>
    <div id="embedMap" style="width: 400px; height: 300px;">
        <!--Google map will be embedded here-->
    </div>
</body>
</html>                                		

Try it:



Related Articles

  1. Maven Overview


comments powered by Disqus