HTML5 Geolocation Tutorial : HTML5 Geolocation Example

With HTML5 you can access the geolocation of the user.

Browser wise Geolocation Support

Detecting Geolocation Support

You can use the Modernizr JavaScript library to check if the user’s browser supports geolocation.

if(Modernizr.geolocation) {
	// HTML5 geolocation supported
} else {
	// HTML5 geolocation not supported
}

Using Geolocation with HTML 5

Here is a small sample you can use to get started with geolocation in HTML5.

If you are testing this locally on your machine, then you will need to use a local web server to run this sample.

<!DOCTYPE html>
<html>
<head>
	<title>HTML 5 Geolocation Sample Page</title>
	<script src="modernizr-2.5.2.js"></script>
	<script src="jquery-1.6.1.min.js"></script>
	<script type="text/javascript">
		var jQ = jQuery.noConflict();

		function useGeolocation(position) {
			var latitude = position.coords.latitude;
			var longitude = position.coords.longitude;

			jQ("#latitude").html(latitude);
			jQ("#longitude").html(longitude);
		}

		function onGeolocationError(error) {
			alert("Geolocation error - code: "
                        + error.code + " message : " + error.message);
		}

		jQ(document).ready(function(){
			if(Modernizr.geolocation) {
				jQ("#geolocation").html("is supported.");

				navigator.geolocation.getCurrentPosition(
  useGeolocation, onGeolocationError);

			} else {
				jQ("#geolocation").html("is not supported.");
			}

		});
	</script>
</head>
<body>

<b>Geolocation</b> : <span id="geolocation"></span> <br />
<b>Latitude</b> : <span id="latitude"></span> <br />
<b>Longitude</b> : <span id="longitude"></span> <br />

</body>
</html>

Screen Shots

Success: User allowed the geolocation access

Error: User denied the geolocation access

Example Source Code

You can download the HTML5 Gelolocation Example source code from here.

Exit mobile version