HTML5 Geolocation

Kanya Srinisavan

The Geolocation API of HTML5 helps in identifying the user’s location, which can be used to provide location specific information or route navigation details to the user.

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.

The Geolocation API protects the user’s privacy by mandating that the user permission should be sought and obtained before sending the location information of the user to any website. So the user will be prompted with a popover or dialog requesting for the user’s permission to share the location information. The user can accept or deny the request.

user permission required

Now let us first understand the API and then plot your location in the Google Maps.

The first step in using any of the APIs in HTML5 is to check for its compatibility with the browser.

Check for Browser compatibility

The geolocation property of the global navigator object helps in detecting the browser support for the Geolocation API.

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

Get the user’s current location

The current location of the user can be obtained using the getCurrentPosition function of the navigator.geolocation object. This function accepts three parameters – Success callback function, Error callback function and 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.

if (navigator.geolocation) {
					
// Get the user's current position
navigator.geolocation.getCurrentPosition(showPosition, showError, optn);
} else {
	alert('Geolocation is not supported in your browser');
}
  1. Success callback function
    This callback function is 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. A position object contains a timestamp property denoting the time at which the location data is retrieved and a coords object.

    The coords object has the following properties

    • Latitude, longitude – Geographic coordinates in decimal degrees
    • Accuracy – Accuracy level of the latitude and longitude coordinates in meters. Bigger the number lesser is the accuracy
    • Altitude – Height of the position above the sea level in meters
    • AltitudeAccuracy – Denotes how far off the altitude position could be from the actual attitude value obtained in meters. Bigger the number lesser is the accuracy
    • Heading – Provides 360 degree heading information
    • Speed – Indicates relative speed in meters per second
    function showPosition(position) {
    document.write('Latitude: '+position.coords.latitude+'Longitude: '+position.coords.longitude);
    }
  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 circumstances

    • Unknown Error occurred
    • Request timed out
    • User has denied to share the location information
    • Location information itself is unavailable
    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

    It describes the options to use while retrieving the user’s location.

    • enableHighAccuracy: Boolean. If true, the user agent will try to provide the most accurate position. This can result in slower response time and higher power consumption. Is false, less accurate position will be obtained. Default value is false.
    • Timeout: Positive long value. It denotes the maximum time (in milliseconds) that the user agent can take to respond with the location data. Default value is Infinity.
    • maximumAge: Positive long value. 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.
    if (navigator.geolocation) {
    var optn = {
    			enableHighAccuracy : true,
    			timeout : Infinity,
    			maximumAge : 0
    		};
    					 navigator.geolocation.getCurrentPosition(showPosition, showError, optn);
    } else {
    		alert('Geolocation is not supported in your browser');
    }

Track Location changes

The watchPosition() can be used to get the location data at regular intervals. The success callback function is invoked automatically as and when the device or the useragent position changes. The parameters to this function is similar to the getCurrentPosition() function. It returns a watch ID value which can be used to unregister the success callback function by passing it to the clearWatch() function.

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;
	}
}

Show My Location on Google Maps

In order to plot your location on Google Maps we can make use of Google Maps API along with Geolocation API.

  1. First of all, we should 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);
  2. 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
    var mapOptions = {
    				zoom : 12,
    				center : googlePos,
    				mapTypeId : google.maps.MapTypeId.ROADMAP
          				};
    	var mapObj = document.getElementById('mapTxt');
    	var googleMap = new google.maps.Map(mapObj, mapOptions);
  3. Create a marker at the location as given below
    var markerOpt = {
    		map : googleMap,
    		position : googlePos,
    		title : 'Hi , I am here',
    		animation : google.maps.Animation.DROP
    		};
    	var googleMarker = new google.maps.Marker(markerOpt);

    In the above code marker options indicate the following

    • Map – Map object where the marker should appear
    • Position – latlng position at which the marker should be displayed
    • Title – Title that should appear when we hover on the marker
  4. Find the address of your location using the reverse geocoding API and show the address obtained when you click on the marker.
    var geocoder = new google.maps.Geocoder();
    	geocoder.geocode({
    		'latLng' : googlePos
    	}, function(results, status) {
    		if (status == google.maps.GeocoderStatus.OK) {
    			if (results[1]) {
    			var popOpts = {
    			content : results[1].formatted_address,
    			position : googlePos
    			};
    		var popup = new google.maps.InfoWindow(popOpts);
    								google.maps.event.addListener(googleMarker, 'click', function() {
    								popup.open(googleMap);
    						});
    			} else {
    				alert('No results found');
    		}
    		} else {
    			alert('Geocoder failed due to: ' + status);
    		}
    });
  5. Sample Code

    <!DOCTYPE html>
    <html>
    <head>
    <title>Sample Map</title>
    <style>
    #mapdiv {
    	margin: 0;
    	padding: 0;
    	width: 500px;
    	height: 500px;
    }
    </style>
    
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
    <script>
    	var watchId = null;
    	function geoloc() {
    	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 showPosition(position) {
    		var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    		var mapOptions = {
    			zoom : 12,
    			center : googlePos,
    			mapTypeId : google.maps.MapTypeId.ROADMAP
    		};
    		var mapObj = document.getElementById('mapdiv');
    		var googleMap = new google.maps.Map(mapObj, mapOptions);
    		var markerOpt = {
    			map : googleMap,
    			position : googlePos,
    			title : 'Hi , I am here',
    			animation : google.maps.Animation.DROP
    		};
    		var googleMarker = new google.maps.Marker(markerOpt);
    		var geocoder = new google.maps.Geocoder();
    		geocoder.geocode({
    			'latLng' : googlePos
    			}, function(results, status) {
    				if (status == google.maps.GeocoderStatus.OK) {
    				if (results[1]) {
    					var popOpts = {
    						content : results[1].formatted_address,
    						position : googlePos
    					};
    				var popup = new google.maps.InfoWindow(popOpts);
    				google.maps.event.addListener(googleMarker, 'click', function() {
    				popup.open(googleMap);
    			});
    				} else {
    					alert('No results found');
    				}
    				} else {
    					alert('Geocoder failed due to: ' + status);
    				}
    			});
    			}
    
    			function stopWatch() {
    				if (watchId) {
    					navigator.geolocation.clearWatch(watchId);
    					watchId = null;
    
    				}
    			}
    
    		function showError(error) {
    		var err = document.getElementById('mapdiv');
    		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 onload="geoloc()">
    		<p id = 'mapdiv'></p>
    		<button onclick="stopWatch()">
    			Stop
    		</button>
    	</body>
    </html>

    Google Map

    Conclusion

    Start exploring Google maps API and see what more features you can build on top of the sample given above.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Alex Dred
  • Anonymous

    I ran code from my server and found that I was 2,000 miles away(I am in Cairns and got a map from Barack st in Sydney)??? May be my computer is spied on by psychiatric Australian Federal Police?

  • Rudy Hamilton

    Geolocation isn’t an HTML5 feature. It is a JavaScript API.

    • Anonymous

      Yep, I think a whole lot of things got lumped in under “HTML5″ for lazy marketing types. At least _we_ know that not all of this is actually HTML. /shrug

    • Anonymous

      Word of caution: the coordinates object that you get back from the API is not always a regular JavaScript object in certain browsers. This means that you’ll get an exception if you try to JSON.stringify it, for example. If you need a plain JavaScript object, just create a new one yourself and cherry-pick the standard values over into it.

  • Francisc

    if(‘geolocation’ in navigator)

  • Anonymous

    nice

  • Jayesh Kawli

    Hey such a nice article! I would like to reference your code in one of my next projects. Though I was aware of HTML5 geolocatin feature, I just got to know that google maps can be embedded along with the geolocation coordinates.
    Thanks,
    Jayesh.