Geolocation API
The Geolocation API allows web applications to get the user's geographic location.
Getting the Location
getCurrentPosition
<button id="getLocation">Get Location</button>
<p id="location"></p>
<script>
document.getElementById('getLocation').addEventListener('click', function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
document.getElementById('location').innerHTML = "Geolocation is not supported by the browser.";
}
});
function showPosition(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
document.getElementById('location').innerHTML =
"Latitude: " + lat + "<br>Longitude: " + lon;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
document.getElementById('location').innerHTML = "Location permission denied.";
break;
case error.POSITION_UNAVAILABLE:
document.getElementById('location').innerHTML = "Location unavailable.";
break;
case error.TIMEOUT:
document.getElementById('location').innerHTML = "Request timeout.";
break;
default:
document.getElementById('location').innerHTML = "Unknown error.";
}
}
</script>
watchPosition
<p id="tracking"></p>
<script>
const watchID = navigator.geolocation.watchPosition(function(position) {
document.getElementById('tracking').innerHTML =
"Lat: " + position.coords.latitude +
", Lon: " + position.coords.longitude;
});
// Stop tracking
// navigator.geolocation.clearWatch(watchID);
</script>
Case Study: Student Monitoring System
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Campus Location Monitoring System</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', sans-serif;
background: #f0f2f5;
padding: 2rem;
}
.container {
max-width: 800px;
margin: 0 auto;
}
h1 {
color: #1e3a5f;
margin-bottom: 2rem;
text-align: center;
}
.card {
background: white;
padding: 1.5rem;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 1rem;
}
.card h2 {
color: #1e3a5f;
margin-bottom: 1rem;
font-size: 1.2rem;
}
.btn {
background: #3498db;
color: white;
border: none;
padding: 0.8rem 1.5rem;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
width: 100%;
}
.btn:hover {
background: #2980b9;
}
.btn-danger {
background: #e74c3c;
}
.btn-danger:hover {
background: #c0392b;
}
.location-info {
margin-top: 1rem;
padding: 1rem;
background: #f8f9fa;
border-radius: 4px;
display: none;
}
.location-info.active {
display: block;
}
.location-info p {
margin-bottom: 0.5rem;
}
.location-info strong {
color: #1e3a5f;
}
.map-placeholder {
width: 100%;
height: 200px;
background: #e9ecef;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
color: #666;
margin-top: 1rem;
}
.status {
padding: 0.5rem;
border-radius: 4px;
margin-top: 1rem;
display: none;
}
.status.active {
display: block;
}
.status.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.status.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.status.tracking {
background: #fff3cd;
color: #856404;
border: 1px solid #ffeeba;
}
</style>
</head>
<body>
<div class="container">
<h1>Campus Location Monitoring System</h1>
<div class="card">
<h2>Get Current Location</h2>
<button class="btn" id="getLocation">Get My Location</button>
<div class="location-info" id="locationInfo">
<p><strong>Latitude:</strong> <span id="lat">-</span></p>
<p><strong>Longitude:</strong> <span id="lon">-</span></p>
<p><strong>Akurasi:</strong> <span id="accuracy">-</span> meter</p>
<p><strong>"Time:"</strong> <span id="timestamp">-</span></p>
</div>
<div class="map-placeholder" id="mapPlaceholder">
Map will appear here
</div>
<div class="status" id="status"></div>
</div>
<div class="card">
<h2>Real-time Tracking</h2>
<button class="btn" id="startTracking">Start Tracking</button>
<button class="btn btn-danger" id="stopTracking" style="display: none; margin-top: 0.5rem;">
Stop Tracking
</button>
<div class="location-info" id="trackingInfo">
<p><strong>Last Position:</strong></p>
<p><strong>Latitude:</strong> <span id="trackLat">-</span></p>
<p><strong>Longitude:</strong> <span id="trackLon">-</span></p>
<p><strong>Update count:</strong> <span id="updateCount">0</span></p>
</div>
<div class="status" id="trackingStatus"></div>
</div>
</div>
<script>
let watchID = null;
let updateCount = 0;
// Get Current Position
document.getElementById('getLocation').addEventListener('click', function() {
if (!navigator.geolocation) {
showStatus('status', 'error', 'Geolocation is not supported by the browser.');
return;
}
showStatus('status', 'tracking', 'Getting location...');
navigator.geolocation.getCurrentPosition(
function(position) {
document.getElementById('lat').textContent = position.coords.latitude;
document.getElementById('lon').textContent = position.coords.longitude;
document.getElementById('accuracy').textContent = position.coords.accuracy;
document.getElementById('timestamp').textContent = new Date(position.timestamp).toLocaleString('id-ID');
document.getElementById('locationInfo').classList.add('active');
document.getElementById('mapPlaceholder').textContent =
`Map: ${position.coords.latitude}, ${position.coords.longitude}`;
showStatus('status', 'success', 'Location successfully obtained!');
},
function(error) {
let message = '';
switch(error.code) {
case error.PERMISSION_DENIED:
message = 'Location permission denied. Enable permission in browser settings.';
break;
case error.POSITION_UNAVAILABLE:
message = 'Location unavailable. Make sure GPS is on.';
break;
case error.TIMEOUT:
message = 'Request timeout. Try again.';
break;
default:
message = 'Unknown error.';
}
showStatus('status', 'error', message);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
});
// Watch Position
document.getElementById('startTracking').addEventListener('click', function() {
if (!navigator.geolocation) {
showStatus('trackingStatus', 'error', 'Geolocation is not supported by the browser.');
return;
}
updateCount = 0;
watchID = navigator.geolocation.watchPosition(
function(position) {
updateCount++;
document.getElementById('trackLat').textContent = position.coords.latitude;
document.getElementById('trackLon').textContent = position.coords.longitude;
document.getElementById('updateCount').textContent = updateCount;
document.getElementById('trackingInfo').classList.add('active');
showStatus('trackingStatus', 'tracking',
`Tracking active - Update #${updateCount}`);
},
function(error) {
showStatus('trackingStatus', 'error', 'Tracking error: ' + error.message);
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
);
document.getElementById('startTracking').style.display = 'none';
document.getElementById('stopTracking').style.display = 'block';
});
document.getElementById('stopTracking').addEventListener('click', function() {
if (watchID !== null) {
navigator.geolocation.clearWatch(watchID);
watchID = null;
}
showStatus('trackingStatus', 'success', 'Tracking stopped.');
document.getElementById('startTracking').style.display = 'block';
document.getElementById('stopTracking').style.display = 'none';
});
function showStatus(elementId, type, message) {
const status = document.getElementById(elementId);
status.textContent = message;
status.className = 'status active ' + type;
}
</script>
</body>
</html>
Everyday Case Study
Case: A developer needs to display the user's location on a registration form.
<form>
<label for="location">Your Location:</label>
<input type="text" id="location" readonly>
<button type="button" onclick="getLocation()">Auto-fill</button>
</form>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById('location').value =
position.coords.latitude + ', ' + position.coords.longitude;
});
}
}
</script>
Best Practices
- Ask for permission clearly: Explain why the location is needed
- Handle errors: Always handle errors
- Fallback: Provide a manual option if permission is denied
- Privacy: Don't store the location without permission
- Accuracy: Use enableHighAccuracy as needed
Summary
The Geolocation API allows web applications to get the user's location. Use it carefully and respect the user's privacy.