Computer >> Computer tutorials >  >> Programming >> Javascript

Latitude and longitude of the user's position in JavaScript?


latitude and longitude

The geolocation property returns a Geolocation object that can be used to locate the user's position. The object provided was navigator.geolocation.This might be annoying to the privacy of the user, therefore, the position is not available unless the user approves it.

syntax

navigator.geolocation;

This method returns the latitude and longitude of the user's position without taking any parameter as an argument.

Example

In this example using position.coords, which is a read-only property, along with javascript's geolocation property, the latitude and longitude of the user's location is found out and the result is displayed in the output.

<html>
<body>
<p id = "location"></p>
<script>
   var loc = document.getElementById("location");
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(getPos);
   }
   function getPos(position) {
      loc.innerHTML = "Latitude: " + position.coords.latitude +
      " </br> Longitude: " + position.coords.longitude;
   }
</script>
</body>
</html>

Output

Latitude: 17.4381439
Longitude: 78.3948683