fastread homefastrread library fastread menu

HTML5 : Geolocation

Tutorial by:Franklin Dessi      Date: 2016-08-26 00:52:37

❰ Previous Next ❱

Geolocation enables us to track down our physical presence at any place. The information assists us in letting people know about our location. The user can decide whether the information regarding the location may be shared or not as he will be prompted accordingly. All the latest versions of the browsers support this feature (including IE9).


<!DOCTYPE html>
<p id = "fstrd">Your physical location</p>
<button onclick = "getLocation()">Latitude and Longitude</button>
var x = document.getElementById("fstrd"); function getLocation() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition( showLocation,displayError);
else {x.innerHTML = "Your browser does not support the Geolocation feature";}
function showLocation(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
function displayError(error) { switch(error.code) {
x.innerHTML = "Permission issues, Access Denied." break;
case error.POSITION_UNAVAILABLE: x.innerHTML = "As of now, Location
info is not available." break;
case error.TIMEOUT:
x.innerHTML = "There seems to be a timeout issue, Please try later."
case error.UNKNOWN_ERROR:
x.innerHTML = "Error cause not found." break;


If we observe the preceding code, we can see that the position.coords.latitude and the position.coords.longitude help us in retrieving information about the coordinates of our physical location with respect to the latitude and longitude of that place.

The navigator.geolocation function will help us determine whether the browser supports this feature.

We have also used the switch command to define the various errors that the user

might come across due to some reason or the other.

The output of the code will vary depending on the browser. Let's look at the way the user is prompted in IE with regards to the permission required to share his physical location, as shown in the following screenshot:


The message prompted to the user in Opera will be slightly different. In Opera, we will see the following screenshot:

Once the user grants the permission and clicks on the Latitude and Longitude button, the following screenshot would be displayed:


There is also a watchPosition method, where we can track the location whenever the user moves to a different location.

❰ Previous Next ❱


Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website