01 July, 2019

How to get the current location latitude and longitude in java script ?

In this article we will see how to get the latitude and longitude. As we know java script is a high-level programming language,  it gives many libraries to implement in our program to achieve real time necessities.  Here we have used Navigator and Geolocation in our program.

We have used the Navigator.geolocation , its a read-only property returns a Geolocation object that gives Web content access to the location of the device.

sample-geolocation.html

<!DOCTYPE html>
<html>
<body>
<title>Get Current Location Sample</title>
<h4>Click the below button to get your current location coordinates.</h4>
<button onclick="getLocation()">Get My Current Location</button>
<div id="displayId"></div>
<script>
var display = document.getElementById("displayId");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayPosition);
  } else {
    display.innerHTML = "Geolocation is not supported by this browser.";
  }
}
function displayPosition(position) {
  display.innerHTML = "<br>Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>

Now, we can see the output on the browser as below.








Happy Learning. 


No comments:

Post a Comment