The geolocation API is useful for locating the user’s location. We can get the geographical position of the user only when the user approves it. It is one of the useful HTML APIs to be used on a web application. Network routing addresses such as IP addresses, MAC addresses, RFID, etc are used to locate the latitude and longitude coordinates of the user. The user’s privacy is protected as the geolocation API sends a notification to the user where the user can allow or deny the sharing of the location.

Geolocation methods are as follows:

  • getCurrentPosition()

    used to identify the user’s current location and returns a position object with data.

  • watchPosition()

    used to return the value if the device location changes

  • clearWatch()

    used to clear the previous watch position call

Global Navigator object is used by geolocation API which can be created as follows:

var loc=navigator.geolocation


<html> <body> <h1>Knowledge2life</h1> <button onclick="getLocation()">Try It</button> <p id="demo"></p> <script> var x = document.getElementById("demo"); 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> </html>