-
Hajipur, Bihar, 844101
The HTML Geolocation API allows web applications to access the geographical location of a user's device. It can retrieve:
Latitude
Longitude
Accuracy
Altitude (if available)
Speed and direction (if available)
⚠️ Note: This feature works only in secure contexts (HTTPS), and the user must grant permission.
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
<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) {
document.getElementById("output").innerText =
"Latitude: " + position.coords.latitude +
", Longitude: " + position.coords.longitude;
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location unavailable.");
break;
case error.TIMEOUT:
alert("Request timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
</script>
Method | Description |
---|---|
getCurrentPosition() |
Gets the current location once |
watchPosition() |
Monitors and returns location continuously |
clearWatch(id) |
Stops monitoring the position |
Q1. Use navigator.geolocation.getCurrentPosition()
to show latitude and longitude.
Q2. Add a button that fetches location on click.
Q3. Display an error message if the user denies location permission.
Q4. Use watchPosition()
to track real-time movement.
Q5. Display a live Google Maps link using the coordinates.
Q6. Show coordinates only when accessed over HTTPS.
Q7. Log errors for debugging using showError()
function.
Q8. Update a <div>
with coordinates every 5 seconds using watchPosition
.
Q9. Create a fallback message for unsupported browsers.
Q10. Use clearWatch()
to stop location tracking with a "Stop" button.
Q1: Which method gets the user’s location once?
Q2: What must the user do before location data is accessed?
Q3: Which of the following is NOT part of the position.coords object?
Q4: What is required for Geolocation to work?
Q5: What method continuously tracks position?
Q6: Which error code means the user denied permission?
Q7: What does clearWatch() do?
Q8: Where is the Geolocation API accessed from?
Q9: Which one is a valid error callback for Geolocation?
Q10: Geolocation API is part of: