34. Geolocation API (Geolocation API - GPS Location)
Finding the Latitude and Longitude with the user's permission
Real-life analogy
Just as the Zomato or Google Maps app finds your address by itself the moment you open it, this API does the same thing.
Explanation
The HTML5 Geolocation API allows you to find the GPS location of the user's device:
- Function:
navigator.geolocation.getCurrentPosition(success, error) - Security rule: Location works only over a secure HTTPS connection.
- The browser shows the user a popup: "Do you want to give this site your location?" The location is obtained only if the user clicks Allow.
Golden rules
- Always add error handling (in case the user refuses to give the location).
Common mistake
Testing location over local HTTP (it gets blocked).
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
<button onclick="getLoc()" style="background: #059669; color: white; border: none; padding: 8px 14px; border-radius: 4px; font-size: 13px; font-weight: bold; cursor: pointer;">
Find my location (GPS)
</button>
<p id="locOutput" style="font-size: 13px; color: #334155; margin-top: 10px;"></p>
<script>
function getLoc() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(pos) => {
document.getElementById('locOutput').innerHTML =
"Latitude (Lat): " + pos.coords.latitude + "<br>Longitude (Long): " + pos.coords.longitude;
},
(err) => {
document.getElementById('locOutput').innerText = "Error: permission was not granted.";
}
);
}
}
</script>
</body>
</html>
Quick quiz
Which condition is mandatory for the Geolocation API to get the user's location?
- The website being paid
- The user granting Allow permission
- Bluetooth being on
- Being logged in to Google
Show answer
Answer: The user granting Allow permission
No website can get the location without the user's explicit permission.