HTML Geolocation API
The Geolocation API gives web applications access to the user’s latitude and longitude, and optionally their accuracy, altitude, heading, and other information. It can use:
- GPS (on mobile)
- Wi-Fi
- IP address
- Cell towers

Syntax
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
Example: Get Latitude & Longitude
<!DOCTYPE html>
<html>
<head>
<title>Geolocation Example</title>
</head>
<body>
<h2>Click to Get Your Location</h2>
<button onclick="getLocation()">Get Location</button>
<p id="output"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
document.getElementById("output").innerText = "Geolocation is not supported.";
}
}
function showPosition(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
document.getElementById("output").innerText = `Latitude: ${lat} \nLongitude: ${lon}`;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
</script>
</body>
</html>
Geolocation Object Properties
| Property | Description |
|---|---|
| coords.latitude | Latitude in decimal degrees |
| coords.longitude | Longitude in decimal degrees |
| coords.accuracy | Accuracy of the location in meters |
| coords.altitude | Altitude above sea level (may be null) |
| coords.speed | Current ground speed in m/s (optional) |
| timestamp | Time when location was retrieved |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com