Real-time Tracking Example
Implement real-time vehicle tracking using WebSocket and mapping libraries.
This example uses Leaflet for mapping, but you can adapt it to any mapping library.
Complete Implementation
Real-time vehicle tracking with map visualization
<!DOCTYPE html> <html> <head> <title>Vehicle Tracking</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> <style> #map { height: 500px; } .vehicle-info { padding: 10px; background: #f0f0f0; } </style> </head> <body> <div id="map"></div> <div id="vehicle-info" class="vehicle-info"></div> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <script> class VehicleTracker { constructor() { // Initialize map this.map = L.map('map').setView([34.0522, -118.2437], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.map); this.vehicles = new Map(); // Store vehicle markers this.initializeWebSocket(); } initializeWebSocket() { // Change this to your domain this.ws = new WebSocket('ws://localhost:8000/ws/vehicles/'); this.ws.onmessage = (event) => { const data = JSON.parse(event.data); this.updateVehicles(data.vehicles); }; this.ws.onclose = () => { console.log('WebSocket disconnected'); setTimeout(() => this.initializeWebSocket(), 2000); }; } updateVehicles(vehicles) { vehicles.forEach(vehicle => { const { id, latitude, longitude, state, battery_level } = vehicle; // Create or update marker let marker = this.vehicles.get(id); if (!marker) { marker = L.marker([latitude, longitude]).addTo(this.map); this.vehicles.set(id, marker); } else { marker.setLatLng([latitude, longitude]); } // Update popup content marker.bindPopup(` <b>Vehicle ${id}</b><br> Status: ${state}<br> Battery: ${battery_level}% `); // Update info panel document.getElementById('vehicle-info').innerHTML = ` <h3>Vehicle ${id}</h3> <p>Status: ${state}</p> <p>Battery: ${battery_level}%</p> <p>Location: ${latitude.toFixed(4)}, ${longitude.toFixed(4)}</p> `; }); } } // Initialize tracker const tracker = new VehicleTracker(); // Clean up on page unload window.addEventListener('beforeunload', () => { if (tracker.ws) { tracker.ws.close(); } }); </script> </body> </html>
Key Features
- Real-time map updates
- Vehicle status visualization
- Battery level monitoring
- Automatic reconnection
- Popup information windows
- Status panel updates
Implementation Notes
- Replace WebSocket URL with your domain
- Add error handling as needed
- Consider adding authentication
- Add loading states
- Implement custom markers
- Add route visualization
Testing the Implementation
Steps to verify the tracking system
- Start your Django development server
- Open the HTML file in a browser
- Send test updates using the Python or JavaScript API client
- Verify markers appear and update on the map
- Check that popups show correct information
- Test WebSocket reconnection by restarting the server