Real Examples of Using the Geolocation API for Live Tracking

Posted by

Learn how to track and update real-time user location in JavaScript with simple, working examples.

Learn how to track and update real-time user location in JavaScript with simple, working examples.

Introduction

Real-time location tracking isn’t just for delivery apps or ride-sharing platforms anymore; it’s everywhere.

From fitness dashboards to “find my friend” maps, live tracking helps users see motion as it happens.

The good news? You don’t need any external service or complex library to do it.
 You can track a user’s location in real time using pure JavaScript thanks to the Geolocation API.

In this article, we’ll go beyond theory and look at real, copy-paste-ready examples that show you how to track, update, and visualize location changes as they happen.


1. A Quick Overview of the Geolocation API

The Geolocation API is built into modern browsers and allows web apps to access the user’s physical location (latitude and longitude).

It works through:

  • GPS (most accurate on mobile)
  • Wi-Fi
  • Cell towers
  • IP geolocation (on desktops)

The API provides two key methods:

navigator.geolocation.getCurrentPosition(success, error, options);
navigator.geolocation.watchPosition(success, error, options);

The first gets a single position, the second continuously watches and updates it, perfect for live tracking.


2. Example 1: Get Current Location

Before we start tracking, let’s first get a one-time location snapshot.

<button id="locate">Get My Location</button>
<p id="output">Click the button to get your coordinates.</p>

<script>
const output = document.getElementById('output');

document.getElementById('locate').addEventListener('click', () => {
if (!navigator.geolocation) {
output.textContent = 'Geolocation is not supported by your browser.';
return;
}

navigator.geolocation.getCurrentPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
output.textContent = `Latitude: ${latitude}, Longitude: ${longitude}`;
},
(err) => {
output.textContent = 'Error: ' + err.message;
}
);
});
</script>

This gives you the user’s current coordinates once.
Now let’s make it move.


3. Example 2: Live Tracking with watchPosition()

For real-time tracking, use watchPosition().
It keeps listening for location changes and calls your callback every time something changes.

<p id="status">Waiting for location updates...</p>

<script>
const status = document.getElementById('status');

if (navigator.geolocation) {
const watchId = navigator.geolocation.watchPosition(
(pos) => {
const { latitude, longitude, speed } = pos.coords;
status.textContent = `
Latitude: ${latitude.toFixed(5)} | Longitude: ${longitude.toFixed(5)}
${speed ? `| Speed: ${speed.toFixed(2)} m/s` : ''}
`;
},
(err) => {
status.textContent = 'Error: ' + err.message;
},
{ enableHighAccuracy: true, maximumAge: 0 }
);

// Stop watching after 5 minutes
setTimeout(() => navigator.geolocation.clearWatch(watchId), 300000);
} else {
status.textContent = 'Geolocation not supported.';
}
</script>

✅ This updates the coordinates every few seconds as you move.
If you open it on a phone and walk around, you’ll see your coordinates changing live.


4. Example 3: Tracking on a Map (Using Google Maps)

Let’s make tracking visual by plotting it on a map.

<div id="map" style="height:300px;width:100%;"></div>

<script>
let map, marker;

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: { lat: 0, lng: 0 },
});
marker = new google.maps.Marker({ map });
}

function updatePosition(pos) {
const { latitude, longitude } = pos.coords;
const location = { lat: latitude, lng: longitude };
marker.setPosition(location);
map.setCenter(location);
}

if (navigator.geolocation) {
navigator.geolocation.watchPosition(updatePosition);
}

// Google Maps script
</script>

<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

Now the map marker moves with your device in real time, just like in a navigation app.

💡 Tip: For open-source projects, use Leaflet.js instead of Google Maps.


5. Example 4: Displaying the Path (Route Tracking)

If you want to visualize where the user has been, store the coordinates and draw a path.

<div id="map" style="height:300px;"></div>

<script>
let map, path = [], polyline;

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: { lat: 0, lng: 0 },
});
polyline = new google.maps.Polyline({
map,
path,
strokeColor: "#007bff",
strokeWeight: 4,
});
}

function updateTrack(pos) {
const { latitude, longitude } = pos.coords;
const newPoint = { lat: latitude, lng: longitude };
path.push(newPoint);
polyline.setPath(path);
map.setCenter(newPoint);
}

if (navigator.geolocation) {
navigator.geolocation.watchPosition(updateTrack);
}
</script>

<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

Now you can watch your live trail being drawn as you move, perfect for running apps or delivery route tracking.


6. Handling Permissions and Errors

Geolocation requests require explicit user permission.
 Always handle these cases gracefully:

navigator.geolocation.getCurrentPosition(success, (error) => {
switch (error.code) {
case error.PERMISSION_DENIED:
alert('You denied location access.');
break;
case error.POSITION_UNAVAILABLE:
alert('Position unavailable.');
break;
case error.TIMEOUT:
alert('Location request timed out.');
break;
default:
alert('An unknown error occurred.');
}
});

Always explain why you need their location before prompting.


7. Best Practices for Live Tracking

  • Use high accuracy only when needed. GPS drains battery quickly.
  • Stop tracking when the user leaves the page or disables tracking.
  • Throttle updates if you’re storing or sending positions to a backend.
  • Use HTTPS browsers to block location access on insecure origins.
  • Respect privacy, never share or store location without consent.

Live tracking is powerful, but with great power comes responsibility.


8. Real-World Use Cases

Here’s where Geolocation-based live tracking shines:

It’s not just for big platforms; you can build smaller, privacy-respecting live trackers for any app.


9. Browser Support


10. Complete Mini Tracker Demo

Here’s a clean, working demo you can test on your phone:

<h3>Live Tracker</h3>
<p id="info">Tracking...</p>

<script>
const info = document.getElementById('info');

if (navigator.geolocation) {
const watchId = navigator.geolocation.watchPosition(
(pos) => {
const { latitude, longitude, accuracy } = pos.coords;
info.textContent = `
Lat: ${latitude.toFixed(5)} | Lng: ${longitude.toFixed(5)} | Accuracy: ${accuracy}m
`;
},
(err) => {
info.textContent = 'Error: ' + err.message;
},
{ enableHighAccuracy: true, maximumAge: 0 }
);

window.onbeforeunload = () => navigator.geolocation.clearWatch(watchId);
} else {
info.textContent = 'Geolocation not supported on this device.';
}
</script>

This updates coordinates continuously, no libraries, no dependencies.


Conclusion

The Geolocation API is one of the most underrated features in modern web development.

With just a few lines of JavaScript, you can turn your web app into a live tracker following movement, drawing routes, or updating maps in real time.

No frameworks. No backend complexity. Just the open web.

Pro Tip: Combine watchPosition() with a lightweight map library like Leaflet.js to build a fully functional tracker in under 100 lines of code.


Call to Action

Would you build a live tracker for deliveries, workouts, or something else?
Share your project idea in the comments and bookmark this post for when you’re ready to bring it to life.

Leave a Reply

Your email address will not be published. Required fields are marked *