Horje
Learn HTML Geolocation API Code

Tips (Total 8)


# Tips-1) What is HTML Geolocation API

The HTML Geolocation API is used to locate a user's position.

The HTML Geolocation is used to get the geographical position of a user. Due to privacy concerns, this position requires user approval. Geo-location in HTML5 is used to share the location with some websites and be aware of the exact location. It is mainly used for local businesses, and restaurants, or showing locations on the map. It uses JavaScript to give latitude and longitude to the backend server.

Most browsers support Geolocation API. Geo-location API uses a global navigator object. In this article, we will know HTML Geolocation, various properties, methods & their implementation through examples.

Syntax:

var loc = navigator.geolocation

 

Example of HTML Geolocation API

Try following Example
index.html
Example: HTML

<!DOCTYPE html>
<html>
 
<body>
    <p>Displaying location using Latitude and Longitude</p>
 
    <button class="geeks" onclick="getlocation()">
        Click Me
    </button>
    <p id="demo1"></p>
 
    <script>
        let variable1 = document.getElementById("demo1");
        function getlocation() {
            navigator.geolocation.getCurrentPosition(showLoc);
        }
        function showLoc(pos) {
            variable1.innerHTML =
                "Latitude: " +
                pos.coords.latitude +
                "<br>Longitude: " +
                pos.coords.longitude;
        }
    </script>
</body>
   
</html>


# Tips-2) How to create HTML Locate the User's Position

The HTML Geolocation API is used to get the geographical position of a user.

Since this can compromise privacy, the position is not available unless the user approves it.

Note: Geolocation is most accurate for devices with GPS, like smartphones.

Try GEO Location

Follow the Example

index.html
Example: HTML
<p><button class="w3-btn w3-blue w3-round" onclick="getLocation()">Try It</button></p>
<div id="mapholder"></div>
<script src="https://maps.google.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU"></script>
<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)
  {
  var lat=position.coords.latitude;
  var lon=position.coords.longitude;
  var latlon=new google.maps.LatLng(lat, lon)
  var mapholder=document.getElementById('mapholder')
  mapholder.style.height='250px';
  mapholder.style.width='100%';

  var myOptions={
  center:latlon,zoom:14,
  mapTypeId:google.maps.MapTypeId.ROADMAP,
  mapTypeControl:false,
  navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
  };
  var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
  var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
  }

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>


# Tips-3) What type of browsers will support for HTML Geo Location

The numbers in the table specify the first browser version that fully supports Geolocation.

Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.

# Tips-4) How to Use HTML Geolocation

The getCurrentPosition() method is used to return the user's position.

The example below returns the latitude and longitude of the user's position:

Example of using HTML GEO LOCATION

Try following Example
index.html
Example: HTML
<!DOCTYPE html>
<html>
<body>
<h1>HTML Geolocation</h1>
<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

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

Output should be:

Example of using HTML GEO LOCATION

Example explained:

The example above is a very basic Geolocation script, with no error handling.


# Tips-5) How to add Handling Errors and Rejections

The second 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 of Handling Errors and Rejections

The second 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:

index.html
Example: HTML
<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

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

Output should be:

Example of Handling Errors and Rejections

# Tips-6) What is Location-specific Information

This page has demonstrated how to show a user's position on a map.

Geolocation is also very useful for location-specific information, like:

 


# Tips-7) How to create HTML getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object on success. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:

Property Returns
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)

# Tips-8) How to create HTML Geolocation Object - Other interesting Methods

The Geolocation object also has other interesting methods:

The example below shows the watchPosition() method. You need an accurate GPS device to test this (like smartphone):

Example of Geolocation Object - Other interesting Methods

Follow the Example

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
const x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(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 should be:

Example of Geolocation Object - Other interesting Methods

Share on: