Sometimes the task is to find the current location of the user and then display the location coordinates on a web page or display the location on a map. Using HTML and javascript code, this article demonstrates the process of getting the user's current location in an HTML page. Demonstrated by using two different examples. In the first example, you can get the user's current location and then display the location coordinates on an HTML page. In the second example, the open source Leaflet map library is used to obtain and display the user's current location on a map.
Code Explanation and Design Steps −
Step 1 − Create an HTML file and start writing code.
Step 2 - Create a label
and set it to display the location coordinates.
Step 3 - Create a button and call the function getYourLoc() when the button is clicked.
Step 4 - Write code in the <script> tag and create two functions getYourLoc() and showMyPos(pos). </script>
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 position to the
tag created earlier, using showMyPos(pos). test result.
Important file used − locationfile.html
The Chinese translation of<!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>
To see the results, open the loactionfile.html file in your browser. Now click on the button to find the user's current location. The coordinates will be displayed on the html page.
Code Explanation and Design Steps −
Step 1 − Create an HTML file and start writing code.
Step 2 - Create a label
and set it to display the location coordinates.
Step 3 - Create a button and call the function getYourLoc() when the button is clicked.
Step 4 − Inside the