Get Longitude And Latitude Of Current Location using Google Map

In this article, we will learn how to get the latitude and longitude of our current location.

Follow the steps :

Step 1 :

Create the HTML component.

<!DOCTYPE html>
<html>
<body>
    <p>Click the button to get your coordinates.</p>
    <button onclick="getLocation()">Click now</button>
    <p id="demo"></p>
   </body>
</html>

Step 2 :

In the HTML body area, write the Javascript code that will be used. Create the HTML component.

<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>Let's view the entire code now (i.e both HTML and Javascript)

Let’s view the entire code now (i.e both HTML and Javascript

<!DOCTYPE html>
<html>
<body>
    <p>Click the button to get your coordinates.</p>
    <button onclick="getLocation()">Click now</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>

Submit a Comment

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

Subscribe

Select Categories