What is HTML5 Geolocation

HTML5 Geolocation or Geolocation API is used to get user Physical Location or geographical position using Device Sensors. Earlier IP based location was used, but now Geo Location is more popular as it is more accurate. As Geolocation is related to user privacy, first browser will grant your permission.

Chrome 50 and above doesn't support geolocation API on non secure origins( i.e. http). For Secured origin ( https), geolocation api will work. You can test your code on Firefox, Edge, IE and Safari browsers.


Geolocation Permission

Getting user physical location comes under user privacy. HTML5 geolocation will always grant permission from user to check geolocation. If a user allows, geolocation will work, else geolocation will not work.

HTML5 Geolocation
Html5 Geolocation permission

Check Geolocation support

Geolocation is supported in http protocol & HTML5 Based browsers only. IE 8 and low doesn't support Geolocation.

Check Geo Location

Geolocation Code


<script>
    if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success);
		
        function success(position){
		    alert(position.coords.latitude + ", "+ position.coords.longitude )
        }
    }
    else
    {
		alert("Geolocation is not supported")
    }
</script>
			

Google Map Direction API

We all have used google direction in google maps. Let create the same Direction API using HTML5 Geolocation and google maps.


<button onclick="getLocation()"> Get Direction </button>		
<script>
	function getLocation()
  {
  if(navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError); 
	return false;
    }
  else{
     alert("Geolocation is not supported by this browser.";)
      }
  }
	
function showPosition(position)
  {
  var lat=position.coords.latitude;        // latitude position
  var lon=position.coords.longitude;       // longitude position
  var acc=position.coords.accuracy;        // longitude accuracy in meters
  
   window.open("https://www.google.com/maps/dir/" + lat + "," + lon + "/Tech+Altum, +Noida,+Uttar+Pradesh+201301,+India/@28.585731,77.1751928,12z/data=!3m1!4b1!4m8!4m7!1m0!1m5!1m1!1s0x390ce45eed7c8971:0xcbb6c33c43ba8f02!2m2!1d77.313203!2d28.582582"); 
  }
  
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;
    }
  }
</script>		

HTML5 Geolocation is not supported in IE 8 and Below. To run geolocation code locally, please use localhost. Geolocation is not permitted on file protocol. Make sure your device location sensors or GPS is on.