Section 6 · Chapter 16
HTML5 Geolocation API
The HTML Geolocation API is used to locate a user's position. Since this can compromise privacy, the position is not available unless the user approves it.
Live Code Example
Click Try it Yourself » to test Geolocation coordinate retrieval live in the playground.
Example: getCurrentPosition API
<button onclick="getLocation()">Get Coordinates</button>
<p id="demo"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("demo").innerHTML = "Geolocation is not supported.";
}
}
function showPosition(position) {
document.getElementById("demo").innerHTML =
"Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Try it Yourself »
💻 Chapter 16 Hands-On Code Challenge
Build a Weather Location Tracker script using navigator.geolocation.getCurrentPosition() with error handling:
Chapter 16 Key Takeaways
navigator.geolocation.getCurrentPosition()retrieves the user's current GPS position once.- Geolocation API requires an explicit HTTPS connection (Secure Context) in modern web browsers.
watchPosition()continuous tracks location updates as the user moves.
Chapter 16 Quiz
1. What security context is strictly required for Geolocation APIs to function?