How to locate the user's position in HTML?


Sometimes, the task is to find the user’s current position and then to show the location coordinates on the webpage or show the location on a map. Using HTML and javascript code this process of getting the current location of the user in an HTML page is demonstrated in this article. This is shown by using two different examples. In the first example, the current location of the user can be fetched and then the location coordinates are displayed on the HTML page. In the second example, an open-source Leaflet map library is used to fetch and then display the user’s current location on a map.

Example 1: Finding the current location of the user and showing the location coordinates on the html page.

Code Explanation and Design Steps

Step 1 − Make an HTML file and start writing the code.

Step 2 − Make a tag

and set it to show the location coordinates.

Step 3 − Make a button and call the function getYourLoc() on the button click.

Step 4 − Inside the <script> tags write the code and make two functions getYourLoc() and showMyPos(pos).

Step 5 − Write the javascript code in getYourLoc() to find the current location using navigator.geolocation.getCurrentPosition() and then call showMyPos(pos).

Step 6 − Add the location to

tag made earlier, using showMyPos(pos). Check the result.

Important file used − locationfile.html

Code For parentFolderFile.html:

<!DOCTYPE html>
<html>
   <body>
      <p>Show My Location Coordinates</p>
      <button onclick="getYourLoc()">Get the location coordinates</button>
      <p id="showloc"></p> 
      <script>
      var x = document.getElementById("showloc");
      function getYourLoc() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showMyPos);
         } else {
            x.innerHTML = "No support for this in the browser.";
         }
      }
      function showMyPos(pos) {
         x.innerHTML = "My Latitude is : " + pos.coords.latitude +
         "<br>My Longitude is : " + pos.coords.longitude;
      }
      </script>
   </body>
</html>

Viewing The Result

For seeing the result open the loactionfile.html in a browser. Now click the button to find the current location of the user. The coordinates are displayed on the html page.

Example 2: Finding the current location of the user and showing the location coordinates on the map.

Code Explanation and Design Steps

Step 1 − Make an HTML file and start writing the code.

Step 2 − Make a tag

and set it to show the location coordinates.

Step 3 − Make a button and call the function getYourLoc() on the button click.

Step 4 − Inside the <script> tags write the code and make three functions getYourLoc() , showMyPos(pos), and showmap(pos).

Step 5 − Write the javascript code in getYourLoc() to find the current location using navigator.geolocation.getCurrentPosition() and then call both the functions showMyPos(pos) and showmap(pos).

Step 6 − For showing the map, in the function showmap(pos), including the leaflet library, use a base map, set the marker and pass the current location coordinates for marking the map location.

Step 7 − Add the location to

tag made earlier, using showMyPos(pos). Also, show the map. Check the result.

Important file used − locationfile11.html

Code For locationfile11.html:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title>Leaflet Map</title>
   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
   <style type="text/css">
      body{
         margin: 0;
         padding: 0;
      }
      #map {
         width: 100vw;
         height: 100vh;
      }
   </style>
</head>
<body>
   <p>Show My Location Coordinates</p>
   <button onclick="getYourLoc()">Get the location coordinates</button>
   <p id="showloc"></p>
   
   <div id="map"></div>
   // the leaflet library for making maps
   
      <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
      <script>
      var x = document.getElementById("showloc");
      // get the current location of the user
      function getYourLoc() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showMyPos);
         } else {
            x.innerHTML = "No support for this in the browser.";
         }
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showmap);
         } else {
            x.innerHTML = "No map here.";
         }
      }
      function showMyPos(pos) {
         var lat=pos.coords.latitude;
         var lon=pos.coords.longitude;
         x.innerHTML = "My Latitude is : " + lat +
         "<br>My Longitude is : " + lon;
      }
      function showmap(pos){
         var latc=pos.coords.latitude;
         var lonc=pos.coords.longitude;
         const map = L.map('map', {
            center: [latc, lonc],
            zoom: 3
         });
         //Adding a base map
         L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
         const marker1 = L.marker([latc, lonc]).addTo(map);
      }
   </script>
</body>
</html>

Viewing The Result

For seeing the result open the loactionfile11.html in a browser. Now click the button to find the current location of the user. The coordinates are seen and marked on the map.

In this HTML article, using two different examples, the ways to show how to find the user’s current location is shown. First the method is given where the location coordinates are displayed on the page after fetching the location and then the way of using these coordinates on a map is given while showing the location in HTML page.

Updated on: 18-Apr-2023

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements