All posts

Real-Time Location Tracking and Route Playback with Django and PostGIS

Learn how to stream GPS coordinates into Django Channels, store spatial points in PostGIS, and query historical breadcrumbs for smooth route playback.

3 min read

Building location-aware apps usually starts with a simple requirement: show an asset moving across a map in real time, and let users replay that trip later. While pushing coordinates over WebSockets is fairly straightforward, handling high-frequency telemetry, storing it efficiently, and retrieving reconstructed paths without crippling the database requires deliberate architecture.

Over several projects, I settled on a stack using Django Channels for live point ingestion and broadcast, backed by GeoDjango with PostGIS to store coordinates and render indexed route playbacks.

The Spatial Schema

For point-in-time tracking, every ping needs an asset reference, timestamp, coordinates, and optional metadata such as speed or heading. PostGIS gives us the PointField, which indexes coordinates with an R-Tree index (GIST) for spatial queries.

# models.py
from django.contrib.gis.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class TrackingSession(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="trips")
    title = models.CharField(max_length=120)
    created_at = models.DateTimeField(auto_now_add=True)

class LocationPing(models.Model):
    session = models.ForeignKey(TrackingSession, on_delete=models.CASCADE, related_name="pings")
    point = models.PointField(srid=4326)
    speed = models.FloatField(null=True, blank=True)
    timestamp = models.DateTimeField(db_index=True)

    class Meta:
        indexes = [
            models.Index(fields=["session", "timestamp"]),
        ]
        ordering = ["timestamp"]

Using SRID 4326 stores standard WGS 84 GPS coordinates (longitude and latitude). The compound index on session and timestamp ensures fast chronological lookups when replaying a journey.

Handling Live Streaming via Channels

Mobile clients or GPS transponders emit points every few seconds. An asynchronous WebSocket consumer parses incoming coordinate payloads, saves them, and distributes the update to all clients watching that specific session group.

# consumers.py
import json
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from channels.db import database_sync_to_async
from django.contrib.gis.geos import Point
from .models import LocationPing, TrackingSession

class LiveTrackingConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.session_id = self.scope["url_route"]["kwargs"]["session_id"]
        self.group_name = f"track_{self.session_id}"

        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.group_name, self.channel_name)

    async def receive_json(self, content):
        lon = content.get("longitude")
        lat = content.get("latitude")
        speed = content.get("speed", 0.0)
        timestamp = content.get("timestamp")

        # Persist to database
        await self.save_ping(lon, lat, speed, timestamp)

        # Broadcast update to viewers
        await self.channel_layer.group_send(
            self.group_name,
            {
                "type": "location_update",
                "longitude": lon,
                "latitude": lat,
                "speed": speed,
                "timestamp": timestamp,
            }
        )

    async def location_update(self, event):
        await self.send_json(event)

    @database_sync_to_async
    def save_ping(self, lon, lat, speed, timestamp):
        point = Point(float(lon), float(lat), srid=4326)
        LocationPing.objects.create(
            session_id=self.session_id,
            point=point,
            speed=speed,
            timestamp=timestamp
        )

This keeps live tracking latency well under 100 milliseconds across connected dashboards. For production scale, it is usually better to buffer writes through Redis or Celery batches, but writing directly inside an asynchronous task works reliably for dozens of concurrent active devices.

Querying and Serializing for Playback

Route playback presents a different challenge: pulling thousands of raw points can cause client-side rendering bottlenecks on interactive maps like Mapbox or Leaflet. PostGIS allows us to aggregate points directly into a single LineString or output lightweight GeoJSON collections with ease.

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.gis.db.models.aggregates import Collect
from .models import LocationPing

class RoutePlaybackView(APIView):
    def get(self, request, session_id):
        pings = (
            LocationPing.objects
            .filter(session_id=session_id)
            .order_by("timestamp")
            .values("point", "timestamp", "speed")
        )

        # Format points as GeoJSON features for client-side interpolation
        coordinates = [
            {
                "coords": [item["point"].x, item["point"].y],
                "timestamp": item["timestamp"].isoformat(),
                "speed": item["speed"],
            }
            for item in pings
        ]

        return Response({"session_id": session_id, "route": coordinates})

On the frontend, route playback does not require streaming past points over WebSockets. You simply fetch this ordered array once via HTTP, calculate frame deltas between timestamps, and interpolate the marker position over time using requestAnimationFrame.

Practical Performance Tips

  • Avoid coordinate reversals: Remember that PostGIS and GeoJSON expect [Longitude, Latitude] (X, Y), whereas many mobile GPS SDKs return [Latitude, Longitude]. Always confirm order at ingestion.
  • Filter stationary noise: Devices sitting still often emit jittering coordinates due to GPS drift. Drop pings where the distance between the new point and the previous point is below an error threshold (for instance, 3 meters) unless a timeout forces a heartbeat ping.
  • Simplify long paths: For long completed trips, run PostGIS's ST_SimplifyPreserveTopology over the aggregated LineString to strip redundant nodes before serving historical views.

Have a project in mind?

I build and run web apps end to end.

Get in touch