> For the complete documentation index, see [llms.txt](https://docs.blynk.io/en/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.blynk.io/en/html-widget-developer-guide/historical-and-map-data.md).

# Historical & Map Data

Fetch recorded datastream values and location tracks for a period.

**Periods** — both methods take the same `period` values:

| Period                                                                                                    | Meaning                                                                                                                        |
| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `'ONE_HOUR'`, `'SIX_HOURS'`, `'DAY'`, `'WEEK'`, `'MONTH'`, `'THREE_MONTHS'`, `'SIX_MONTHS'`, `'ONE_YEAR'` | A fixed window ending now                                                                                                      |
| `'CUSTOM'`                                                                                                | An explicit `from` / `to` range in Unix milliseconds                                                                           |
| `'RANGE_PICKER'`                                                                                          | **Web only** (`isRangePickerSupported()`). Follows the dashboard's date-range picker and keeps pushing new results — see below |

### Get historical data

> Returns recorded values of up to 10 datastreams for a period, raw or aggregated.

```js
bridge.getHistoricalData(options)  // → Promise<HistoricalDataResult>
```

**Parameters**

| Name                               | Type     | Required                                            | Description                                                                                            |
| ---------------------------------- | -------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `options.period`                   | `string` | yes                                                 | One of the [periods](https://docs.blynk.io/en/html-widget-developer-guide/historical-and-map-data.md)  |
| `options.from`                     | `number` | CUSTOM only                                         | Start of the range, Unix ms                                                                            |
| `options.to`                       | `number` | CUSTOM only                                         | End of the range, Unix ms. Must be **strictly greater** than `from`; the span must not exceed 365 days |
| `options.offset`                   | `number` | no                                                  | Number of points to **skip**, for `RAW_DATA` pagination. Non-negative integer, default `0`             |
| `options.dataStreams`              | `array`  | **yes — for every period, `RANGE_PICKER` included** | 1 to 10 datastream descriptors                                                                         |
| `options.dataStreams[].index`      | `number` | yes                                                 | 0-based datastream index                                                                               |
| `options.dataStreams[].sourceType` | `string` | yes                                                 | `'RAW_DATA'`, `'MIN'`, `'MAX'`, `'AVG'`, `'SUM'` or `'COUNT'`                                          |

`sourceType` values:

| Value                      | Description                                                                           |
| -------------------------- | ------------------------------------------------------------------------------------- |
| `RAW_DATA`                 | Individual recorded points, no aggregation. `granularity` is `null` for these streams |
| `MIN`, `MAX`, `AVG`, `SUM` | Minimum, maximum, average or sum per time bucket                                      |
| `COUNT`                    | Number of points per time bucket                                                      |

**Resolves with**

```ts
{
  streams: Array<{
    index:       number,        // 0-based datastream index
    granularity: string | null, // 'MINUTE' | 'FIFTEEN_MINUTES' | 'HOURLY' | 'DAILY' | 'WEEKLY' | 'MONTHLY'
                                // null when sourceType was RAW_DATA
    values: Array<{ x: number,  // Unix ms
                    y: number }>// bucket value, or the raw recorded value
  }>
}
```

The server picks the bucket size from the period and `sourceType`. Null-check `granularity` before you display it.

**Rejects with**

All validation runs **before** anything is sent, and fails with code `invalid_request`. Branch on `code`; the messages below are current but not a stable API.

| Condition                             | Message                                                                         |
| ------------------------------------- | ------------------------------------------------------------------------------- |
| `options` or `period` missing         | `'period' is required`                                                          |
| Unknown `period`                      | `'period' must be one of: …`                                                    |
| `CUSTOM` without `from` or `to`       | `CUSTOM period requires 'from' and 'to' timestamps`                             |
| `from` / `to` not a finite number     | `'from' must be a finite number` / `'to' must be a finite number`               |
| `from >= to`                          | `'from' must be less than 'to'` — equal timestamps are rejected too             |
| Span over 365 days                    | `'to' - 'from' must not exceed one year (365 days)`                             |
| Bad `offset`                          | `'offset' must be a non-negative integer`                                       |
| `dataStreams` not an array            | `'dataStreams' must be an array`                                                |
| `dataStreams` empty or longer than 10 | `'dataStreams' must carry from 1 to 10 datastreams`                             |
| `dataStreams[N]` not an object        | `dataStreams[N] must be an object`                                              |
| Bad `dataStreams[N].index`            | `dataStreams[N].index must be a non-negative integer`                           |
| Bad `dataStreams[N].sourceType`       | `dataStreams[N].sourceType must be one of: RAW_DATA, MIN, MAX, AVG, SUM, COUNT` |

Other codes: `request_timeout` (no result within 30 seconds — `Historical data request timeout (30s)`), `server_error`, `device_unavailable`, `bridge_destroyed`.

**Out-of-range indexes are not reported per entry.** If *every* `dataStreams[].index` is past the widget's list, the call rejects (`No valid datastream indexes`). If only some are, it resolves without those streams and without an error — validate indexes against `getValues()` if you need to detect that.

**Example**

```js
// Aggregated, fixed window
bridge.getHistoricalData({
  period: 'DAY',
  dataStreams: [{ index: 0, sourceType: 'AVG' }, { index: 1, sourceType: 'MIN' }]
})
  .then(({ streams }) => streams.forEach(s =>
    s.values.forEach(({ x, y }) => plot(s.index, x, y, s.granularity ?? 'RAW_DATA'))))
  .catch(err => bridge.log('History error: ' + err.code));

// Raw data, next page — keep period/from/to identical and grow offset by the points received
bridge.getHistoricalData({
  period: 'ONE_HOUR', offset: 500,
  dataStreams: [{ index: 1, sourceType: 'RAW_DATA' }]
}).then(({ streams }) => appendChart(streams));

// Custom range — the last 7 days
const to = Date.now();
bridge.getHistoricalData({
  period: 'CUSTOM', from: to - 7 * 24 * 60 * 60 * 1000, to,
  dataStreams: [{ index: 1, sourceType: 'AVG' }]
}).then(({ streams }) => renderChart(streams));
```

**`RANGE_PICKER` (web only)**

`RANGE_PICKER` hands range selection to the dashboard's own date-range picker. It is a **subscription**:

1. The first `getHistoricalData({ period: 'RANGE_PICKER', dataStreams: […] })` call registers the widget and resolves with the data for the range the picker shows now.
2. Every later picker change pushes a fresh result to `onHistoricalDataUpdated`. Those pushes are not Promise resolutions.

```js
const HISTORY_STREAMS = [{ index: 0, sourceType: 'AVG' }];

bridge.setCallbacks({ onHistoricalDataUpdated: ({ streams }) => renderChart(streams) });  // first

if (bridge.isRangePickerSupported()) {
  bridge.getHistoricalData({ period: 'RANGE_PICKER', dataStreams: HISTORY_STREAMS })
    .then(({ streams }) => renderChart(streams));
} else {
  // Mobile: draw your own period control and request fixed or CUSTOM ranges
  bridge.getHistoricalData({ period: 'DAY', dataStreams: HISTORY_STREAMS })
    .then(({ streams }) => renderChart(streams));
}
```

> Register `onHistoricalDataUpdated` **before** subscribing, so the first push isn't lost. `dataStreams` is required here too.

***

### Get map data

> Returns the recorded location points of a `LOCATION` datastream for a period.

```js
bridge.getMapData(options)  // → Promise<MapDataResult>
```

**Parameters**

| Name             | Type     | Required    | Description                                                                                                                            |
| ---------------- | -------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `options.index`  | `number` | yes         | 0-based index of an assigned `LOCATION` datastream                                                                                     |
| `options.period` | `string` | yes         | One of the [periods](https://docs.blynk.io/en/html-widget-developer-guide/historical-and-map-data.md), including `RANGE_PICKER` on web |
| `options.from`   | `number` | CUSTOM only | Start of the range, Unix ms                                                                                                            |
| `options.to`     | `number` | CUSTOM only | End of the range, Unix ms. Must be **strictly greater** than `from`. There is no 365-day cap                                           |

**Resolves with**

```ts
{ points: Array<{ ts: number, latitude: number, longitude: number }> }   // [] when there are none
```

Map data is never aggregated and takes no `sourceType`.

**Rejects with** `invalid_request` (`'index' is required`, a non-integer index, or the same period and range rules as `getHistoricalData`), `request_timeout` (30 seconds — `Map data request timeout (30s)`), `server_error`, `device_unavailable`, `bridge_destroyed`. An index that isn't a `LOCATION` datastream fails on the host side.

**Example**

```js
bridge.setCallbacks({ onMapDataUpdated: ({ points }) => drawTrack(points) });   // web RANGE_PICKER pushes

const period = bridge.isRangePickerSupported() ? 'RANGE_PICKER' : 'DAY';
bridge.getMapData({ index: 0, period })
  .then(({ points }) => drawTrack(points))
  .catch(err => bridge.log('Map error: ' + err.code));
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.blynk.io/en/html-widget-developer-guide/historical-and-map-data.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
