Learn how to build a live map that follows user movement in real time using only JavaScript and the browser’s built-in Geolocation API.

Introduction
You’ve seen it before, apps like Google Maps, Uber, and Strava that track your location and show it updating live.
But here’s something most developers don’t realize:
You can build your own real-time tracking map using nothing more than the Geolocation API and a few lines of JavaScript.
No frameworks.
No server setup.
No external SDKs required.
In this post, you’ll learn how to:
- Access the user’s live location in the browser.
- Display it on a real map.
- Automatically update the position as the user moves.s
- Handle permissions, errors, and best practices
Let’s bring real-time maps to your next web project.
1. What Is the Geolocation API?
The Geolocation API is a native browser feature that lets your web app access the device’s physical location, usually through GPS, Wi-Fi, or mobile networks.
It provides two main methods:
navigator.geolocation.getCurrentPosition(success, error, options);
navigator.geolocation.watchPosition(success, error, options);
getCurrentPosition()Gives you the user’s current coordinates once.watchPosition()Continuously tracks updates in real time.
And yes, it works on mobile browsers too (with permission).
2. Get the User’s Location Once
Let’s start simple: a one-time location request.
<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>
✅ Once the user grants permission, you’ll see their coordinates appear.
Now, let’s make it move in real time.
3. Track Location Live with watchPosition()
watchPosition() keeps listening for changes and updates as the device moves.
<p id="status">Tracking your location...</p>
<script>
const status = document.getElementById('status');
if (navigator.geolocation) {
const watchId = navigator.geolocation.watchPosition(
(pos) => {
const { latitude, longitude, accuracy } = pos.coords;
status.textContent = `
Latitude: ${latitude.toFixed(5)},
Longitude: ${longitude.toFixed(5)},
Accuracy: ±${accuracy}m
`;
},
(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.';
}
</script>
Now you’ve got live updates every few seconds, perfect for tracking movement or navigation.
4. Display the User’s Location on a Map
Let’s make things visual.
You can use Google Maps or the open-source Leaflet.js library.
We’ll use Leaflet since it doesn’t need an API key.
Step 1: Add Leaflet
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
Step 2: Create a Map Container
<div id="map" style="height: 400px;"></div>
Step 3: Initialize the Map and Marker
<script>
const map = L.map('map').setView([0, 0], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
}).addTo(map);
const marker = L.marker([0, 0]).addTo(map);
</script>
Now you have a basic map loaded with OpenStreetMap tiles.
5. Combine It All: Real-Time Tracking on the Map
Here’s the complete code:
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<div id="map" style="height: 400px;"></div>
<script>
const map = L.map('map').setView([0, 0], 15);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
}).addTo(map);
const marker = L.marker([0, 0]).addTo(map);
if (navigator.geolocation) {
navigator.geolocation.watchPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
const coords = [latitude, longitude];
marker.setLatLng(coords);
map.setView(coords, map.getZoom());
},
(err) => console.error(err),
{ enableHighAccuracy: true, maximumAge: 0 }
);
} else {
alert('Geolocation not supported on this device.');
}
</script>
✅ This version tracks your position live and moves the map marker as you move, all using native browser APIs.
6. Optional: Draw the Path (Route Tracking)
If you want to show movement history (like a running route), store previous coordinates and draw a polyline.
const path = [];
const line = L.polyline(path, { color: 'blue' }).addTo(map);
navigator.geolocation.watchPosition((pos) => {
const { latitude, longitude } = pos.coords;
const coords = [latitude, longitude];
path.push(coords);
line.setLatLngs(path);
map.setView(coords);
});
Now you can literally see your route as it’s being drawn live.
7. Handle Permissions and Errors Gracefully
Always handle permissions responsibly:
navigator.geolocation.getCurrentPosition(success, (error) => {
switch (error.code) {
case error.PERMISSION_DENIED:
alert('You denied location access.');
break;
case error.POSITION_UNAVAILABLE:
alert('Location unavailable.');
break;
case error.TIMEOUT:
alert('Request timed out.');
break;
default:
alert('Unknown error.');
}
});
Always explain to users why you need their location before prompting. Transparency builds trust.
8. Security and Privacy Tips
- The Geolocation API only works over HTTPS (except localhost).
- Only request location after user interaction (e.g., button click).
- Never store or share location without consent.
- Stop tracking when it’s no longer needed (
clearWatch).
Privacy isn’t optional; it’s part of good engineering.
9. Real-World Use Cases
Here’s where Geolocation-based real-time maps shine:

These features are easy to implement but instantly raise your app’s value.
10. Browser Support

Conclusion
The Geolocation API gives you everything you need to make your web app aware of the real world.
With just a few lines of JavaScript, you can build live maps, real-time trackers, and route visualizations all powered by the browser itself.
No plugins. No backend. Just the open web.
Pro Tip: Combine the Geolocation API with WebSockets or Firebase for multi-user live tracking (e.g., tracking friends or fleets on one shared map).
Call to Action
Would you use real-time location in your next web app?
Share your ideas in the comments and bookmark this post for your next JavaScript project.


Leave a Reply