HTML Geolocation API

To locate the position of html geolocation API is used, it is done through different data collection mechanisms. Generally this API is used for restaurants and local businesses.

It is device specific API, So browser/device geolocation support is must in order to use it.

Note: For privacy reasons, user is asked for permission to allow location information.

Working and Usage

The Geolocation API is accessed by invoking navigator.geolocatin which prompts the user’s browser to request for permission to access the user’s location data. If the permission is granted by the user than the browser will use the best functionalities available on device to access the location information.

Method for Accessing location

The developer can access the location by using following methods:

  • getCurrentPosition(): This method is used for locating the current position of user.
  • watchPosition(): This function will be automatically called each time when the location of device will changed and it will return the updated location.
<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>
Geolocation API