In Lagos traffic, 'I am five minutes away' is an elastic concept that can mean anything from 'I am outside your gate' to 'I have not left my house yet.' In a physical service marketplace where funds are locked in escrow, both the customer and the artisan need an honest, shared source of truth once a job transitions to `status === 'en_route'`.
Here is how I engineered the end-to-end chat location and live `en_route` navigation system across `chat-location.ts`, `LocationBubbleCard.tsx`, `useJobLocationWebSocket`, and our dedicated `/map` Mapbox GL view—plus the five subtle geolocation bugs we had to squash along the way.

1. From Structured Chat Bubbles to a 3-Layer Deduplication Guard
When a job is accepted—or when a user taps the location pin in the chat composer—`jobLocationMessage()` in `chat-location.ts` serializes a structured location payload containing the job header, street address, and a canonical coordinate URL.
Because React effects and network retries can fire more than once when a job transitions to accepted, we built `shareJobLocationOnce()` with a **three-layer deduplication check**: it inspects existing chat message history, checks an in-memory `Set`/`Map` of in-flight sends, and verifies a per-job key in `localStorage` so a thread never gets spammed with duplicate location cards.
- Inline Map Previews (`LocationBubbleCard.tsx`): Instead of dumping raw coordinates into the chat thread, `JobChat.tsx` parses the message via `readJobLocation()` and renders an interactive map card.
- Reverse-Geocoding Generic Labels: If a saved coordinate arrives with a generic label like `'Saved job location'` or `'Pinned location'`, the bubble automatically reverse-geocodes it into a real street name and caches the result in `reverseGeocodeCache` so scrolling up and down the chat thread never burns Mapbox API quota.
- Live Driving ETA with Haversine Fallback: Each card queries `fetchMapboxRoute()` for real road distance and driving minutes—and if the Directions API is unreachable, gracefully falls back to spherical Haversine distance multiplied by `~2.5 min/km`.
2. Live En-Route WebSocket Streaming (`useJobLocationWebSocket`)
The moment an artisan taps 'I am on my way' (`job.status === 'en_route'`), both participants open a persistent WebSocket connection to `/ws/jobs/<JOB_ID>/location/`:
- Artisan Side (`isArtisan === true`): Starts `navigator.geolocation.watchPosition` and streams live GPS coordinates over the socket—throttled by both elapsed time (`lastSentTimeRef`) and minimum physical displacement (`lastSentCoordsRef`) so standing still at a traffic light doesn't flood the WebSocket.
- Customer Side (`isArtisan === false`): Subscribes to incoming coordinate frames across `JobChat.tsx`, the job detail screen, and `/map`, smoothly sliding the artisan's pulsing blue pin and recalculating the Mapbox driving polyline (`dedicated-map-route-casing` + `dedicated-map-route-line`) in real time.
"The trickiest bug in a two-sided map isn't drawing the blue line—it's making sure the customer's browser GPS doesn't accidentally impersonate the artisan's starting point."
3. Five Geolocation Traps & How We Solved Them
- 1. Role-Safe Origin Resolution (`calculateAndShowRoute`): When a customer opens `/map`, reading `navigator.geolocation` as the route origin would draw a route from the customer to the customer! We enforce a strict origin hierarchy: live WebSocket `artisanCoords` → saved artisan profile coordinates (`/profiles/artisans/:id/`) → browser GPS *only* when `viewerRole === 'artisan'` → nearby road fallback.
- 2. VPN & Out-of-City GPS Sanity Checks (`Math.hypot < 0.75`): If a developer or customer is connected to a European VPN or traveling in another state, browser geolocation produces a 5,000 km route. Both `LocationBubbleCard.tsx` and `map.tsx` run a Euclidean degree-proximity check (`Math.hypot(latDiff, lngDiff) < 0.75`) before trusting browser GPS.
- 3. PostGIS WKT vs. JSON Coordinate Shapes (`extractPoint`): A Django/PostGIS backend doesn't always return `{ latitude, longitude }`. Sometimes it returns WKT strings like `'SRID=4326;POINT (3.5782 6.4538)'`—where **longitude comes first**! `extractPoint` normalizes both numeric/string fields and PostGIS `POINT (lng lat)` strings so pins never end up in the Indian Ocean.
- 4. Tearing Down Stale Watchers: Leaving `watchPosition` alive after a job moves from `en_route` to `arrived` drains battery and leaks background sockets. `useJobLocationWebSocket` immediately clears the watcher and closes the socket on status transition or unmount.
- 5. Escaping Custom HTML Mapbox Markers (`escapeHtml`): Mapbox GL custom DOM markers inject HTML strings for the floating name badges (`'Ola Adeleke (Artisan)'`). Running every dynamic display name through `escapeHtml()` closes the door on DOM XSS.

