> ## Documentation Index
> Fetch the complete documentation index at: https://docs.telemax.com.au/llms.txt
> Use this file to discover all available pages before exploring further.

# Trip Replay

> Fetch trip waypoints, decode polylines, and render trips on Google Maps or Leaflet.

## Overview

Trip replay returns a structured history of vehicle movement as a list of `TripDto` objects. Each trip covers one continuous movement segment with:

| Field                           | Description                                            |
| ------------------------------- | ------------------------------------------------------ |
| `distance`                      | Trip distance in **metres** (not km)                   |
| `duration`                      | Trip duration as ISO 8601 string (e.g. `"PT1H25M"`)    |
| `startAddress` / `endAddress`   | Reverse-geocoded start and end addresses               |
| `startTimeUser` / `endTimeUser` | Trip start/end in the user's configured timezone       |
| `Encoded`                       | Google Polyline Algorithm–encoded path string          |
| `Url`                           | Ready-to-use Google Static Maps URL for a thumbnail    |
| `points`                        | Array of up to 400 waypoints (`lat`, `lng`, `utcTime`) |

**Two endpoints are available:**

| Endpoint                      | When to use                                                 |
| ----------------------------- | ----------------------------------------------------------- |
| `POST /api/GetReplayUserTime` | When your `from`/`to` is expressed in the user's local time |
| `POST /api/GetReplay`         | When your `from`/`to` is in UTC                             |

<Note>
  Both endpoints treat the `from` and `to` parameters as UTC internally. The "user time" variant adjusts the display fields (`startTimeUser`, `endTimeUser`) but the query window is still UTC. Pass ISO 8601 strings (e.g. `2025-05-01T00:00:00Z`).
</Note>

***

## Step 1 — Request a date range

Fetch trips for vehicle `1000` over one week:

<CodeGroup>
  ```bash cURL theme={null}
  curl -s -X POST \
    "https://api.telemax.com.au/api/GetReplayUserTime?id=1000&from=2025-05-01T00:00:00Z&to=2025-05-08T00:00:00Z" \
    -H "Authorization: Bearer YOUR_TOKEN"
  ```

  ```python Python theme={null}
  import requests

  r = requests.post(
      "https://api.telemax.com.au/api/GetReplayUserTime",
      params={
          "id":   1000,
          "from": "2025-05-01T00:00:00Z",
          "to":   "2025-05-08T00:00:00Z",
      },
      headers={"Authorization": "Bearer YOUR_TOKEN"},
  )
  r.raise_for_status()
  trips = r.json()
  print(f"{len(trips)} trip(s) found")
  ```
</CodeGroup>

***

## Step 2 — Inspect the response

Each element in the returned array is a `TripDto`:

```json theme={null}
{
  "id": 103925,
  "distance": 15640.75,
  "duration": "PT1H25M",
  "startAddress": "123 Main St, Sydney NSW 2000",
  "endAddress": "789 Park Ave, Sydney NSW 2021",
  "startTimeUser": "2025-05-01T08:00:00+10:00",
  "endTimeUser": "2025-05-01T09:25:00+10:00",
  "encoded": "mfp_IvhkeLh@d@pFzBrA`@v@eBhA",
  "url": "https://maps.googleapis.com/maps/api/staticmap?path=enc:mfp_IvhkeLh@d@pFzBrA`@v@eBhA",
  "points": [
    { "id": 2505020, "lat": -33.8688, "lng": 151.2093, "utcTime": "2025-05-01T08:00:00" },
    ...
  ]
}
```

<Note>
  Long trips may be split into multiple `TripDto` entries capped at **400 points** each. If you see the same start/end address with sequential timestamps, the trip was chunked — stitch the `points` arrays together and sum the `distance` values.
</Note>

***

## Step 3 — Decode the `Encoded` polyline

The `Encoded` field uses the **Google Polyline Algorithm** format, supported by all major mapping SDKs.

<CodeGroup>
  ```python Python theme={null}
  # pip install polyline
  import polyline

  def decode_trip(trip):
      coords = polyline.decode(trip["encoded"])  # list of (lat, lng) tuples
      print(f"Trip {trip['id']}: {len(coords)} decoded points, "
            f"{trip['distance']:.0f} m, {trip['duration']}")
      return coords

  for trip in trips:
      coords = decode_trip(trip)
  ```

  ```javascript JavaScript theme={null}
  // npm install @mapbox/polyline
  import polyline from "@mapbox/polyline";

  for (const trip of trips) {
    const coords = polyline.decode(trip.encoded); // [[lat, lng], ...]
    console.log(
      `Trip ${trip.id}: ${coords.length} points, ` +
      `${(trip.distance / 1000).toFixed(1)} km, ${trip.duration}`
    );
  }
  ```
</CodeGroup>

***

## Step 4 — Render on a map

<CodeGroup>
  ```javascript JavaScript (Leaflet) theme={null}
  // Assumes Leaflet map initialised as `map`
  import polyline from "@mapbox/polyline";

  for (const trip of trips) {
    const coords = polyline.decode(trip.encoded);

    // Draw the route
    L.polyline(coords, { color: "#0075FF", weight: 3 }).addTo(map);

    // Start marker
    L.marker(coords[0])
      .bindPopup(`<b>Start</b><br>${trip.startAddress}<br>${trip.startTimeUser}`)
      .addTo(map);

    // End marker
    L.marker(coords[coords.length - 1])
      .bindPopup(`<b>End</b><br>${trip.endAddress}<br>${trip.endTimeUser}`)
      .addTo(map);
  }

  // Fit map to all trips
  const allCoords = trips.flatMap(t => polyline.decode(t.encoded));
  if (allCoords.length) map.fitBounds(allCoords);
  ```
</CodeGroup>

***

## Google Static Maps thumbnail

The `Url` field is a pre-built Google Static Maps URL. Use it server-side to generate a trip thumbnail without decoding the polyline:

```python Python theme={null}
import requests

for trip in trips:
    # Download thumbnail (requires a valid Google Maps API key appended)
    thumb_url = trip["url"] + "&size=400x200&key=YOUR_GMAPS_KEY"
    img_data = requests.get(thumb_url).content
    with open(f"trip_{trip['id']}.png", "wb") as f:
        f.write(img_data)
```

***

## Gotchas

* **Distance unit:** `distance` is in **metres**, not kilometres. Divide by 1000 for km.
* **UTC always:** Both `GetReplay` and `GetReplayUserTime` treat `from`/`to` as UTC. The "user time" variant only affects the display fields (`startTimeUser`, `endTimeUser`).
* **400-point cap:** Long trips are split into multiple `TripDto` entries. Sum `distance` across segments for total trip distance.
* **`Encoded` format:** Assumed to be Google Polyline Algorithm format. If your decoder produces invalid coordinates, confirm the encoding with your Telemax contact (GAP-18).
