×

Search anything:

Working with device location using HTML Geolocation API

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 25 minutes

geolocation
The HTML Geolocation API is used to get the current position of the user. The Geolocation API is used using the navigator.geolocation object.The Geolocation interface represents an object able to programmatically obtain the position of the device. It gives Web content access to the location of the device. This allows a Web site or app to offer customized results based on the user's location. The most common sources of location information are IP address, Wi-Fi and Bluetooth MAC address, radio-frequency identification (RFID), Wi-Fi connection location, or device Global Positioning System (GPS) and GSM/CDMA cell IDs. The location is returned with a given accuracy depending on the best location information source available.

Example:

<p>Click the button to get your coordinates.</p>

<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>

Output:

Click the button to get your coordinates.



The example above returns the latitude and longitude of the user's position. It checks if **Geolocation API** is supported or not. If supported, runs the **getCurrentPosition()** method. If not, display a message to the user. If the **getCurrentPosition()** method is successful, it returns a coordinates object to the function specified in the parameter (showPosition). The **showPosition()** function outputs the **Latitude** and **Longitude**.

The parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location.

Example:

<p>Click the button to get your coordinates.</p>

<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, showError);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

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

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      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 unknown error occurred."
      break;
  }
}
</script>

Displaying the Result in a Google Map

For pointing our location on Google map, we need access to Google Maps Platform.
You can check here.

Example:

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

  var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
  "+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";

  document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

We need to put out Google Maps API key in place of YOURKEY and latitude, longitude value in latlon.
We can also find some sample code on the Google Maps API website.

Return values of getCurrentPosition() Method


  • coords.latitude - The latitude as a decimal number (always returned)
  • coords.longitude - The longitude as a decimal number (always returned)
  • coords.accuracy - The accuracy of position (always returned)
  • coords.altitude - The altitude in meters above the mean sea level (returned if available)
  • coords.altitudeAccuracy - The altitude accuracy of position (returned if available)
  • coords.heading - The heading as degrees clockwise from North (returned if available)
  • coords.speed - The speed in meters per second (returned if available)
  • timestamp - The date/time of the response (returned if available)

Geolocation.watchPosition() method


The watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. We can also, optionally, specify an error handling callback function.

Syntax:

navigator.geolocation.watchPosition(success[, error[, options]])

The Parameters are:

  • success : A callback function that takes a Position object as an input parameter.
  • error (Optional) : An optional callback function that takes a PositionError object as an input parameter.
  • options (Optional) : An optional PositionOptions object that provides configuration options for the location watch.

Return value:

An integer ID that identifies the registered handler. The ID can be passed to the Geolocation.clearWatch() to unregister the handler.

Example:

<form>
<input type = "button" onclick = "getLocationUpdate();" value = "Watch Update">
</form>
<script type = "text/javascript">
         var watchID;
         var geoLoc;
         
         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         }
         
         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            } else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }
         
         function getLocationUpdate(){
            
            if(navigator.geolocation){
               
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
            } else {
               alert("Sorry, browser does not support geolocation!");
            }
         }
</script>

Output:



Limitations of Geolocation API


  • This feature is available only in secure contexts (HTTPS).
  • This feature is not supported in all the browsers.
  • On Firefox 24 and older versions, "geolocation" in navigator always returned true even if the API was disabled.
  • Sometimes Geolocation API is less accurate. If we, use VPN, them it may show wrong location.
  • By default, getCurrentPosition() tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy.

Questions

1. The Geolocation API is used using the ______ object?

navigator.geolocation
navigator.location
nav.location
None of the options
The Geolocation API is used using the navigator.geolocation object.

2. which altitude of getCurrentPosition() specifies meters above the mean sea level?

coords.altitude
coords.height
coords.altimeter
None of the options
coords.altitude altitude of getCurrentPosition() specifies meters above the mean sea level.
Working with device location using HTML Geolocation API
Share this