Learn how to access and update a user’s live location in your web app, no libraries, just built-in browser power.

Introduction
Have you ever used a ride-hailing app that updates your position in real time or a map that follows your movement as you walk?
That magic happens thanks to the Geolocation API, a native browser feature that gives web apps access to the device’s GPS.
And the best part?
You don’t need any external libraries or APIs to use it.
In this post, you’ll learn:
- How to request a user’s current location
- How to track their location in real time
- How to handle permissions and errors
- How to visualize updates with practical examples
Let’s build a simple but powerful real-time location tracker using pure JavaScript.
1. What Is the Geolocation API?
The Geolocation API is a built-in web API that allows you to get the user’s current geographical position (latitude and longitude).
You can use it for:
- Real-time tracking (e.g., delivery apps, maps)
- Geofencing or region-based features
- Weather or location-based personalization
- Fitness tracking or navigation tools
It works in all major browsers, desktop and mobile, as long as the user grants permission.
2. Get the User’s Current Location
Let’s start simple: fetch the device’s current coordinates once.
<button id="getLocation">Get My Location</button>
<p id="output"></p>
<script>
const output = document.getElementById('output');
document.getElementById('getLocation').addEventListener('click', () => {
if (!navigator.geolocation) {
output.textContent = 'Geolocation is not supported by your browser.';
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
output.textContent = `Latitude: ${latitude}, Longitude: ${longitude}`;
},
(error) => {
output.textContent = `Error: ${error.message}`;
}
);
});
</script>
✅ This prompts the user for permission, then logs their current latitude and longitude.
3. Track Real-Time Location Updates
To continuously track the user’s position (for navigation or live tracking), use watchPosition() instead.
navigator.geolocation.watchPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`Current position: ${latitude}, ${longitude}`);
},
(error) => {
console.error(error);
},
{ enableHighAccuracy: true, maximumAge: 0 }
);
This keeps calling your callback function every time the position changes, whether the user moves, rotates, or their GPS refines.
Stop Tracking When Needed
You can stop tracking anytime by calling. clearWatch().
const watchId = navigator.geolocation.watchPosition(successCallback, errorCallback);
// later, when you want to stop:
navigator.geolocation.clearWatch(watchId);
This is essential for conserving battery on mobile devices.
4. Display Location on a Map
Let’s make it more visual using a simple integration with Google Maps (or any other mapping library).
<div id="map" style="width:100%; height:300px;"></div>
<script>
let map, marker;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: { lat: 0, lng: 0 },
});
marker = new google.maps.Marker({ map });
}
function updatePosition(position) {
const { latitude, longitude } = position.coords;
const pos = { lat: latitude, lng: longitude };
marker.setPosition(pos);
map.setCenter(pos);
}
if (navigator.geolocation) {
navigator.geolocation.watchPosition(updatePosition);
}
</script>
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Now you’ll see your real-time movement on a map as the marker updates.
(You can also use Leaflet.js for an open-source alternative.)
5. Handle Permissions and Errors Gracefully
Always handle the three possible permission states:
- Granted, the user allows access.
- Denied, they refuse (you should fallback gracefully).
- Prompt the browser asks each time.
Common Errors
navigator.geolocation.getCurrentPosition(
success,
(error) => {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log("User denied location access.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information unavailable.");
break;
case error.TIMEOUT:
console.log("Request timed out.");
break;
default:
console.log("An unknown error occurred.");
}
}
);
Always inform users why you’re requesting location access. Transparency builds trust.
6. High Accuracy vs Battery Life
The API gives you control over how precise you want to be.
navigator.geolocation.getCurrentPosition(success, error, {
enableHighAccuracy: true, // uses GPS
timeout: 10000, // max time (10s)
maximumAge: 0 // don’t use cached data
});
enableHighAccuracy: trueUses GPS for precision but drains battery.maximumAgeHelps reuse cached positions to save energy.
For real-time apps, balance accuracy with performance.
7. Security and Privacy Considerations
The Geolocation API is powerful and sensitive.
Browsers enforce strong privacy controls:
- Works only over HTTPS (except localhost).
- Users must explicitly allow access.
- Some browsers auto-disable location after inactivity.
Never store or share user location without consent, and always give an option to stop tracking.
8. Real Example: Live Position Tracker
Here’s a compact example that updates a user’s position every few seconds in a web UI.
<p>Tracking your location:</p>
<p id="status">Waiting for location...</p>
<script>
const status = document.getElementById('status');
if (navigator.geolocation) {
const watchId = navigator.geolocation.watchPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
status.textContent = `Latitude: ${latitude.toFixed(5)}, Longitude: ${longitude.toFixed(5)}`;
},
(err) => {
status.textContent = 'Error: ' + err.message;
},
{ enableHighAccuracy: true, maximumAge: 0 }
);
// Stop tracking after 5 minutes
setTimeout(() => navigator.geolocation.clearWatch(watchId), 300000);
} else {
status.textContent = 'Geolocation not supported on this device.';
}
</script>
You can enhance this by logging positions, drawing paths, or calculating distances between coordinates.
9. Real-World Use Cases
- Ride and delivery tracking: update driver and passenger positions live.
- Fitness and walking apps: map out routes and distances.
- Weather widgets: display local forecasts automatically.
- Location-based games: track player movement (e.g., AR apps).
- Safety tools: allow users to share live locations in emergencies.
The possibilities are huge, and all start with just one built-in API.
10. Browser Support

Conclusion
The Geolocation API is one of those features that quietly powers countless modern web apps, from delivery tracking to fitness dashboards.
It’s easy to implement, surprisingly powerful, and works natively across browsers.
With just a few lines of JavaScript, your web app can respond to the real world literally.
Pro Tip: Combine navigator.geolocation with a mapping library like Leaflet.js or Mapbox to visualize paths and routes dynamically.
Call to Action
Would you add live tracking to your next web project?
Share your use case or demo in the comments, and bookmark this post if you plan to make your app location-aware soon.


Leave a Reply