HTML Geolocation
The Geolocation API allows you to request a user's location (with their permission) and use it in web applications. This can help show local maps, nearby services, or personalize content based on location. The API is accessed via JavaScript, and the user's privacy is respected with permission prompts.
Key Topics
Geolocation API
The API is accessed through navigator.geolocation
and methods like getCurrentPosition()
.
Requesting Location
Example: Using getCurrentPosition()
to get latitude and longitude.
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position.coords.latitude, position.coords.longitude);
});
Geolocation Example
This example attempts to get the user's location and display coordinates. A full code sample is provided below.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Geolocation Example</title>
</head>
<body>
<p id="status">Requesting location...</p>
<script>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
document.getElementById('status').textContent = 'Latitude: ' + pos.coords.latitude + ', Longitude: ' + pos.coords.longitude;
}, function(error) {
document.getElementById('status').textContent = 'Unable to retrieve location.';
});
} else {
document.getElementById('status').textContent = 'Geolocation not supported by this browser.';
}
</script>
</body>
</html>
Explanation: If the user allows, their coordinates are displayed. If denied or unsupported, an appropriate message is shown.
Key Takeaways
- Geolocation API obtains user's location with permission.
- Useful for location-based services and personalized content.
- Accessed via
navigator.geolocation
and callbacks. - Respect privacy and handle permission denials gracefully.
- Check browser support and provide fallback behavior.