HTML5 Geolocation

Share this article

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.

Frequently Asked Questions about HTML5 Geolocation

How does HTML5 Geolocation work?

HTML5 Geolocation works by allowing a user’s browser to share their location information with a website, if the user permits it. This is done through the Geolocation API, which is built into most modern browsers. The API works by gathering information about nearby cellular towers, Wi-Fi hotspots, and the user’s IP address. This data is then used to estimate the user’s geographical location. The accuracy of this location can vary greatly, depending on the device used and the method of connection.

Is HTML5 Geolocation always accurate?

The accuracy of HTML5 Geolocation can vary greatly. It depends on several factors, including the device being used, the method of connection, and the availability of GPS data. For example, a desktop computer connected via Ethernet may only provide a rough estimate of location, while a smartphone with GPS enabled can provide a much more precise location.

Can I use HTML5 Geolocation without user permission?

No, you cannot use HTML5 Geolocation without the user’s permission. The Geolocation API is designed to respect user privacy, and it requires explicit user consent before it can access location data. When a website attempts to access a user’s location, the browser will prompt the user to either allow or deny the request.

How can I improve the accuracy of HTML5 Geolocation?

The accuracy of HTML5 Geolocation can be improved by using a device with GPS capabilities, such as a smartphone or tablet. Additionally, being connected to a Wi-Fi network can also improve location accuracy, as the Geolocation API can use information about nearby Wi-Fi hotspots to help determine location.

Is HTML5 Geolocation supported in all browsers?

Most modern web browsers support HTML5 Geolocation, including Chrome, Firefox, Safari, and Edge. However, older browsers may not support it. You can check if a browser supports Geolocation by using the ‘navigator.geolocation’ property.

Can HTML5 Geolocation be used for mobile devices?

Yes, HTML5 Geolocation can be used on mobile devices. In fact, it can often provide more accurate location data on mobile devices, as they typically have GPS capabilities.

How can I handle errors in HTML5 Geolocation?

The Geolocation API provides error handling capabilities. If an error occurs while trying to get location data, the API will return an error object, which includes an error code and a message explaining the error. You can use this information to handle the error appropriately in your code.

Can HTML5 Geolocation track a user’s movement?

Yes, HTML5 Geolocation can track a user’s movement. The Geolocation API provides a ‘watchPosition’ method, which continuously returns the user’s updated location as they move. This can be useful for applications such as mapping or navigation.

Is it possible to get a user’s location if they deny permission?

No, if a user denies permission for a website to access their location, the Geolocation API will not provide any location data. It’s important to respect user privacy and only request location data when it’s necessary for the functionality of your website or application.

Can HTML5 Geolocation work offline?

While the Geolocation API can work offline to some extent, it’s important to note that it may not be as accurate. The API relies on data from various sources, including GPS, Wi-Fi, and IP addresses, to determine location. If a device is offline, it may only have access to GPS data, which can limit the accuracy of the location information.

Kanya SrinisavanKanya Srinisavan
View Author
HTML5 Dev Center
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week