HTML Geolocation and Maps

HTML Geolocation and Maps with Examples

In this article, I am going to discuss HTML Geolocation and Maps with Examples. Please read our previous article, where we discussed Drag and Drop in HTML with Examples.

HTML Google Maps

HTML Google Maps is used to display maps on any website. It is quite simple to include a Google Map on a webpage. This can be used by business owners to help customers navigate to their store using Google Maps.

How to add Google Map to the Webpage?
  1. Visit Google Maps. Enter the address of the location you wish to display on your web page in the Search Google Maps text box.
  2. When the map loads, click the Share button.
  3. On the Share window, click the Embed tab.
  4. Select Copy HTML from the menu.
  5. Copy and paste the code into your HTML document.
  6. Save your changes and then preview the page in your browser to see the map.

How to add Google Map to the Webpage?

Example:

In the example below we have embedded a map in our webpage

<!DOCTYPE html>
<html>
<style>
body{
display:flex;
justify-content:center;}
</style>
<body>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3703.5056482171453!2d73.71688411494024!3d21.83802336503438!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x39601d55e43af21f%3A0xb8e23c01a1f6eb18!2sStatue%20of%20Unity!5e0!3m2!1sen!2sin!4v1641230123226!5m2!1sen!2sin" width="500" height="350" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
</body>

</html>
Output:

HTML Geolocation and Maps with Examples

HTML5 Geolocation

HTML5’s geolocation feature is used to share a user’s location with other websites and to keep track of one’s exact location. It’s mostly used by local businesses, restaurants, for listing stores on google maps. JavaScript can record those coordinates and send them to the server, allowing the website to display your current location.

The Geolocation API is supported by the vast majority of web browsers. To determine the user’s location, most geolocation services use network routing addresses like IP addresses, RFID, WIFI, and MAC addresses, or internal GPS devices.

The user’s current position is returned using the getCurrentPosition() method. The below example returns the user’s position’s latitude and longitude:

<!DOCTYPE html>
<html>
<style>
   body{
   display:flex;
   justify-content:center;
   align-items:center;
   flex-direction:column;
   background-color:hotpink;
   font-family:arial;
   color:white;}
button{
background-color:white;
border:none;
padding:10px;}
</style>
<body>

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

<button onclick="getLocation()">Click Me</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>
Output:

HTML5 Geolocation

The first step is to determine whether the browser supports Geolocation.If supported, it will call the getCurrentPosition() function. If not, display a message to the user.

If the getCurrentPosition() method succeeds, it returns the user’s coordinates. The Latitude and Longitude values are returned by the showPosition() function.

User Privacy

Because the user’s location is a privacy concern, the geolocation API protects the user’s privacy by requesting permission before obtaining the user’s location. The Geolocation API provides a notification prompt box to the user, which the user can accept or reject; if the user accepts, then his location is recorded.

Handling Errors

The error callback function is the second parameter of getCurrentPosition. It’s an optional parameter that’s used to manage user denial and issues when retrieving the user’s location. In the event of an error, switch cases can be used to display different messages to the user depending on the problem. Errors that can occur include:

  1. An unknown random error has occurred.
  2. If the user has refused to provide his or her location,
  3. There is no information about the location available.
  4. The request for a location has expired.

The below example fetches the user’s current location. If an error occurs, the user will be prompted about the type of error.

<!DOCTYPE html>
<html>
<head>
<style>
   body{
   display:flex;
   justify-content:center;
   align-items:center;
   flex-direction:column;
   background-color:mediumseagreen;
   font-family:arial;
   color:white;}

</style>
<title>Geolocation API</title>
</head>
<body>
  <h1>Find your Current location</h1>
<button onclick="getlocation()">Click me</button><br>
<div id="location"></div>
<script>
 var x= document.getElementById("location");
    function getlocation() {
    	if(navigator.geolocation){
    		navigator.geolocation.getCurrentPosition(showPosition, showError)
    	  }
    	else
    	{
             alert("Sorry! your browser is not supporting")
         } }
     
     function showPosition(position){
       var x = "Your current location is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " +    position.coords.longitude + ")";
                document.getElementById("location").innerHTML = x;
     }

     function showError(error) {
        switch(error.code){
            case error.PERMISSION_DENIED:
            alert("User denied the request for Geolocation API.");
            break;
        case error.POSITION_UNAVAILABLE:
            alert("USer location information is unavailable.");
            break;
        case error.TIMEOUT:
            alert("The request to get user location timed out.");
            break;
        case error.UNKNOWN_ERROR:
            alert("An unknown error occurred.");
            break;
    }
        }
</script>
</body>
</html>
Output:

HTML Geolocation and Maps with Examples

Displaying Result in Map

The process of displaying a location on a map is very interesting. The exact location on the map is obtained using Html Geolocation services. The below example shows how to use HTML Geolocation to get your current location in a Google Map using latitude and longitude.

<!DOCTYPE html>
<html>

<head>
<title>Display location in map</title>
<style>
   body{
   display:flex;
   justify-content:center;
   align-items:center;
   flex-direction:column;
   background-color:dodgerblue;
   font-family:arial;
   color:white;}

</style>
</head>

<body>

<h2>Click to Display location in map</h2>

<button type="button" onclick="getlocation();">
 Current Position
</button><br><br>
<div id="demo2"
 style="width: 500px; height: 500px"></div>
<script src=
"https://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
 function getlocation() {
 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(showLoc, errHand);
 }
 }
 function showLoc(pos) {
 latt = pos.coords.latitude;
 long = pos.coords.longitude;
 var lattlong = new google.maps.LatLng(latt, long);
 var OPTions = {
  center: lattlong,
  zoom: 10,
  mapTypeControl: true,
  navigationControlOptions: {
  style: google.maps.NavigationControlStyle.SMALL,
  },
 };
 var mapg = new google.maps.Map(
  document.getElementById("demo2"),
  OPTions
 );
 var markerg = new google.maps.Marker({
  position: lattlong,
  map: mapg,
  title: "You are here!",
 });
 }

 function errHand(err) {
 switch (err.code) {
  case err.PERMISSION_DENIED:
  result.innerHTML =
   "The application doesn't have the permission" +
   "to make use of location services";
  break;
  case err.POSITION_UNAVAILABLE:
  result.innerHTML = "The location of the device is uncertain";
  break;
  case err.TIMEOUT:
  result.innerHTML = "The request to get user location timed out";
  break;
  case err.UNKNOWN_ERROR:
  result.innerHTML =
   "Time to fetch location information exceeded" +
   "the maximum timeout interval";
  break;
 }
 }
</script>
</body>

</html>
Before Clicking

Displaying Result in Map

After Clicking

Displaying Result in Map

Location Properties

The properties used in getCurrentPosition() and their return values are listed in the table below.

Location Properties

Geolocation Methods

Geolocation uses the following approaches to make it more interesting and simpler to use.

Geolocation Methods

In the next article, I am going to discuss HTML Web Storage with examples. Here, in this article, I try to explain HTML Geolocation and Maps with Examples and I hope you enjoy this HTML Geolocation and Maps with Examples article.

Leave a Reply

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