HTML Geolocation

By | February 8, 2020

It is a good API for HTML5 it is used for geographical identification of the user for the application. The instructions given can be specified by JavaScript. Are sent to the end server which shows your current status on the web site.HTML5 Geolocation uses most network routing addresses such as IP address WiFi Macs. This feature of HTML5 allows you to find the geographic coordinates of the current location of your website visitor, Latitude and Descent number.Provides better browsing facility for visitors to the site.

Browser Support:-

All modern browsers support this feature of HTML5.

Using HTML Geolocation:-

In this we will see how we can use this feature of HTML. In this example, the latitude and descent of the user’s position returns.


<body>

<button onclick="getLocation()">Test</button>

<h2 id="myId"></h2>

<script>
    var x = document.getElementById("myId");

    function getLocation(){
     if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition);
     } else {
          x.innerHTML = "Geolocation is not supported by this browser";
     }
    } 

    function showPosition(position){
     x.innerHTML = "Latitude: " + position.coords.latitude + 
     "<br>Longitude: " + position.coords.longitude;
    }
</script>

</body>

Displaying the Result in a Map:-

If we want to display any result in the map, then we need access to a map service like Google Map.

Example:-

<script>

   function showPosition(position){
     var latlon = position.coords.latitude + "," + position.coords.longitude;

     var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" +
     latlon + "&zoom=15&size=500x400&sensor=false&key=YOUR_KEY";
     
     document.getElementById("myId").innerHTML = "<img src=''"+img_url+"'>";
   }

</script>

Handling Errors and Rejections:-

Example:-

<script>

function 
showError(error){
 switch(error.code){
     case error.PERMISSION_DENIED:
     x.innerHTML = "User denied the request for Getlocation"
     break;
     case error.POSITION_UNAVAILABLE:
     x.innerHTML = "Location information is unavailable"
     break;
     case error.TIMEOUT:
     x.innerHTML = "The request to get user location timed out"
     break;
     case error.UNKNOWN_ERROR:
     x.innerHTML = "An unknow error occured"
     break;
 }
}

</script>
Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *