HTML Full Course [Day 14] [Hindi] π» | Geolocation API (Basic) π | Mohit Decodes
π HTML Tutorial β Part 14: Geolocation API (Basic)
Welcome to Day 14 of the HTML Full Course [Hindi] by Mohit Decodes! In this lesson, you will learn the basics of the Geolocation API β a powerful feature that lets your website access the user's geographic location.
πΉ What is Geolocation API?
The Geolocation API allows web applications to get the user's current location (latitude and longitude) with their permission. Itβs commonly used in maps, location-based services, weather apps, and more.
βοΈ How to Use Geolocation API (Basic)
Example Code:
html
CopyEdit
<button onclick="getLocation()">Get My Location</button>
<p id="location"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
document.getElementById('location').innerText = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById('location').innerText =
"Latitude: " + position.coords.latitude +
", Longitude: " + position.coords.longitude;
}
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>
π‘ Important Points:
- User permission is required to access location.
- Always handle errors gracefully.
- Useful for enhancing user experience with location-based features.