
# Maps

[Bearer authentication](authentication.md) is required. Responses use `Cache-Control: private, no-store`.

| Method | Endpoint | Input |
| --- | --- | --- |
| GET | `/api/v1/streams` | Query parameters below |
| POST | `/api/v1/parcels/lookup` | JSON body, no query parameters, maximum 4096 bytes |

## Streams

| Parameter | Type and constraints |
| --- | --- |
| `bbox` | Required comma-separated `west,south,east,north` numbers in WGS84 degrees. Longitude −180 to 180, latitude −85.0511287798066 to 85.0511287798066. `west < east`, `south < north`. |
| `datasetId` | Optional string matching `^[A-Za-z0-9-]{1,256}$`. Omission selects the installed dataset. A different ID returns `409 dataset_mismatch`. |

Duplicate or unknown parameters return `400 invalid_request`. Antimeridian crossing is unsupported.

```http
GET /api/v1/streams?bbox=21,52,21.001,52.001
Authorization: Bearer <token>
```

The GeoJSON `FeatureCollection` has `datasetId`, `discoveryCoverage: "display_archive_unqualified"`, `minimumContributingAreaM2`, and `features`. Each feature has a two-position WGS84 `LineString` and `properties.upstreamAreaM2` for its downstream endpoint. Segments can extend beyond the box. Empty results have `features: []`. Archive completeness is unqualified.

Each segment has full source endpoints reconstructed from EPSG:2180 attributes, upstream first and downstream second.
`upstreamAreaM2` describes the downstream endpoint, not every point along the line. Analyze an interior crossing separately.
The service intersects straight geographic segments with the closed bbox, removes identical endpoint/area tile copies and orders results deterministically. Features have no persistent ID.

The minimum contributing area is the release's extraction threshold. No caller zoom, area filter or result limit is supported.
Clipped, quantized or omitted archive features cannot be restored by endpoint reconstruction. An empty result does not establish absent drainage.
These simplified lines do not establish physical connectivity or dependable supply. Pin the returned dataset identity for subsequent queries; mismatches fail rather than substitute another release.

Limits are 64 source tiles, 32 MiB compressed input, 8 MiB decoded per tile, 64 MiB decoded total, 100000 examined features, 8 MiB output, and 15 seconds. Exceeded budgets return `422` errors without truncation.

## Parcel lookup

Use `POST /api/v1/parcels/lookup` for project-free lookup. It does not create a project or save a parcel. Use `location/parcels/discover-point` when you intend to feed its complete candidate to `location/parcels/accept`; see [find and add a parcel](water-devices.md#parcels-with-optional-egib-evidence). A bare parcel number needs its cadastral precinct.
Use the returned parcel geometry directly for local stream screening. Provider failures and invalid geometry
are errors, never missing parcels. The parcel operation has a 30-second deadline.

The body contains exactly one selector without extra fields. `point` is two WGS84 `[longitude,latitude]` numbers, bounded by ±180° and ±90°. `parcelId` is a string of at most 128 characters matching `^\d{6}_[1-9]\.\d{4}\.(?:AR_\d+\.)?\d+(?:/\d+)?$`.

```json
{
	"parcelId": "141201_1.0001.6509"
}
```

`Content-Type: application/json` is required. A `200 matched` response has `status`, `parcelId`, WGS84 `Polygon` or `MultiPolygon` GeoJSON `geometry`, `names`, and `source`. Nullable `names` fields are `voivodeship`, `county`, `municipality`, `precinct`, `parcelNumber`, and `precinctNumber`.

`source` contains `provider: "gugik-uldk"`, `sourceCrs: "EPSG:2180"`, ISO `retrievedAt`, and nullable string `datasource`. The CRS describes input. Retrieval time differs from source update time. A `200 not_found` response contains only `status` and `source`. Response limit is 2000000 bytes.

Response excerpt, with `source` omitted.

```json
{"status": "not_found"}
```

## Errors

Errors contain `error` and `message`. Statuses include `400`, `401`, `403`, `405`, `413`, `415`, `429`, `502`, `503`, and `504`. Parcel provider failures use `parcel_lookup_unavailable`. Map failures include `streams_unavailable`, `invalid_stream_archive`, and the `stream_*_limit_exceeded` or `response_byte_limit_exceeded` budget codes.

## Replace the shared camera conditionally

POST `/api/v1/actions/maps/view/get` with `{ "projectId": "p" }` returns `{view,revision}`. Preserve the returned `map_view` revision when constructing a replacement. POST `/api/v1/actions/maps/view/set` with the intended view, that `expectedRevision`, and a stable presentation-lane envelope.

```json
{
  "projectId": "p",
  "expectedRevision": "<returned-revision>",
  "view": {"center": [21.0122, 52.2297], "projection": "EPSG:4326", "zoom": 12},
  "write": {"sessionId": "<fresh-uuid-1>", "lane": "project-presentation", "sequence": 1}
}
```

Success returns `{view,change}` from the settled receipt. `change` contains `domain: "map_view"`, `revision`, and `updatedAt`. An intervening shared-camera change returns HTTP 409 `precondition_failed` with the bounded current camera and revision, the attempt, and `reread_and_reconsider` recovery. Feature changes and personal viewport changes do not invalidate this basis. Normal map navigation saves only the personal viewport.

Retain the whole attempt and payload until its outcome is known. After a lost response, POST `/api/v1/actions/projects/writes/status` with `{projectId,write}`. `settled` reports `operation: "maps.view.set"` and its original typed result or rejection. A successful status outcome contains the same `{view,change}` result as `maps/view/set`, with `view.center: [x,y]`. Use its view and committed revision for a newly considered intent with a fresh sequence. Exact camera receipts require current `map.edit`. Status never executes a write. `unseen` can mean the request is still running. Resend only the identical attempt and payload; do not advance the lane sequence while uncertain. A changed view, basis, or operation returns `attempt_payload_mismatch`. A settled newer sequence supersedes older ones.

After a definitive conflict, reread and reconsider, then allocate a new sequence for the new intent. The presentation lane is shared with document metadata and other presentation writes. Personal viewports retain their separate revision and lane. Request refusal before owner dispatch has no durable receipt guarantee. Notifications publish after commit and retain the existing crash window and stream reset recovery.

For installed command syntax, read the [CLI command reference](https://tarvena.pl/docs/cli/tarvena-command-reference.md#map).

## Change drawings conditionally

Over MCP, omit `write`: the server supplies it. For HTTP, the six drawing conveniences require `write: {sessionId,lane:"project-presentation",sequence}` and `precondition: {kind:"map-scope",features,memberships,appearances}`. The session ID is a caller-generated UUID. Keep one uncertain request in the lane. Resend the saved request unchanged. Status supports each operation and returns the ordinary setter result.

Create a primitive with a caller-generated `feature.featureId` and this condition.

```json
{
	"kind": "map-scope",
	"features": [{"featureId": "drawing-id", "expected": {"kind": "absent"}}],
	"memberships": [],
	"appearances": []
}
```

`maps/features/get` returns the feature and its owner revision. Member reads also return the complete outgoing `childIds` and removable `appearances` set with its own revision; viewer reads expose null for these complete-set observations. A feature page or a Get for one child does not prove a parent's complete membership. Cross-layer membership is supported.

For replacement, read `maps/features/get` and put the complete observed feature in `expected: {kind:"snapshot",feature}`. The snapshot uses `id` for the returned `featureId` and serialized GeoJSON for `geometry`, or null. Include `geometryProjection` from the returned geometry projection, or null for null geometry. Retain `projectLayerId`, `type`, `properties`, `visible`, `parentId` and `localZIndex`. Convert WKT to equivalent GeoJSON when needed. Geometry object key order is immaterial. A changed CRS conflicts even when coordinates stay equal; property-only patches preserve the current CRS. A replacement of a parented feature also needs its parent's ordered membership and relation fields below.

The required scope follows the affected state.

| Intent | Required conditions |
| --- | --- |
| Primitive creation | The new feature is absent. A new child also checks its parent's ordered membership and relation fields. |
| Primitive replacement | The full target snapshot and any affected parent membership. |
| Group creation | The caller's `groupFeatureId` is absent. Include its empty membership, every requested child's relation fields, and the ordered memberships and relation fields of their current parents. |
| Add or remove group children | The group's relation fields and ordered membership, the existing children and requested children's relation fields, and their affected current parents. |
| Feature deletion or ungroup | Full snapshots of the deletion closure, including empty parents removed by the existing policy. Include a membership for each deleted feature and its current parent, surviving parents' relation fields, and appearances removed by the owner. |

An ordered membership is `{parentId,childIds}`. Relation fields use `expected: {kind:"fields",fields:{existence:{kind:"value",value:{type,projectLayerId}},parentId:{kind:"value",value:parentId},localZIndex:{kind:"value",value:localZIndex}}}`. Sort feature conditions by ID, membership conditions by parent ID, and appearances by the JSON tuple `[domainId,entityType,entityId]`. Use the full observed child order. Do not replace missing observations with empty lists.

Deletion appearances have `{domainId,entityType,entityId,fields:{snapshot:{kind:"value",value:{profileId,baseStyleJson,stateStyleJson}}}}`. Include only removed rows whose entity type is `feature`, `geometry` or `primitive`. A member `maps/features/get` returns that complete removable set for its feature, including other domains. `maps/appearance/get` returns exactly its requested keys, or the project-wide set when no entities are supplied; an empty answer proves absence only for that answered scope. Global read timestamps are not authored fields. Ungroup preserves the existing removal policy and detaches surviving children.

The UI's lifecycle and detail commands use this same condition contract. A field patch covers exactly its authored property keys with `properties.<key>` slots. An absent key is `{kind:"absent"}`. A present null is `{kind:"value",value:null}`. Geometry can be omitted on property-only patches. Geometry, its projection, and rotation are coupled. Every text command compares the observed `shapeId`. Text changes that resize a frame also compare their dependent text fields and geometry. Appearance style patches compare only the top-level style keys they merge. Missing appearance rows have null profile and style defaults. Keys within style records still distinguish absence from explicit null. The owner checks scope completeness atomically with the write.

Successful upsert and group creation return `{feature,changes}`. Delete, ungroup and child edits return `{result:{ok:true},changes}`. Status success equals those results and can supply the snapshot for a subsequent write.

HTTP 409 `precondition_failed` includes the finite operation, attempt, conflicting fields, current domain revision and targeted scope. A scope larger than 12000 UTF-8 bytes or 20 entries in one collection is omitted with `truncated:true`; reread the affected state. Reusing an attempt with changed values, conditions, target or action returns `attempt_payload_mismatch`. A definitive conflict is terminal. Reconsider it with new observations and a fresh sequence. Conditions do not detect a value changed and then restored before comparison. Live drafts and shared undo stacks have no collaborative merge contract.

## Coordinates and source projections

Scalar point selectors accept exactly one form: survey `{x,y}`, named `{easting,northing}` or geographic `{longitude,latitude}`. Survey X is northing; Y is easting. Projected inputs default to EPSG:2180; PL-2000 requires its zone in `projection`. Geographic inputs imply EPSG:4326. Mixed forms are rejected.

### Positions and geometry

A geographic query point uses named fields:

```json
{"point":{"longitude":18.285324,"latitude":51.563507}}
```

Scalar results use `{projection,easting,northing}` and can be reused as point inputs. GeoJSON positions and extent arrays retain their documented order: geographic `[longitude,latitude]`, projected `[easting,northing]`. No third elevation field is accepted on scalar point selectors.

Longitude is between -180 and 180 degrees. Latitude is between -90 and 90 degrees. Individual operations can have narrower bounds. All numbers must be finite. Tarvena does not infer a CRS from magnitude or silently swap coordinates. A geographically valid point outside the installed hydrology dataset is different from malformed input.

The label `EPSG:4326` alone does not specify this API's serialized order. EPSG defines latitude-first axes for that CRS; this API uses longitude-first GeoJSON positions. See [PROJ's axis-order explanation](https://proj.org/en/stable/faq.html#why-is-the-axis-ordering-in-proj-not-consistent).

Public GeoJSON geometries retain that fixed geographic convention. A provenance field describing a provider's source CRS does not change the returned geometry's CRS.

### Bounding boxes

Query bounding boxes contain `[west, south, east, north]` in decimal degrees. The stream endpoint requires west less than east and south less than north, restricts latitude to ±85.0511287798066 degrees, and rejects antimeridian crossings. See the [stream contract](#streams).

Stream segments are straight between their returned endpoints in geographic coordinates. Transforming endpoints alone and connecting them in another projection can change that line. Spatial helpers must preserve crossing topology and document the tolerance used for metric approximations. Metric search bounds must conservatively enclose the full search area.

### Distances, areas, and precision

Fields ending in `M` contain metres; fields ending in `M2` contain square metres. Flow fields ending in `M3s` contain cubic metres per second. Annual volume fields ending in `M3PerYear` contain cubic metres per year. Explicit unit fields on calculation parameters remain authoritative for those parameters.

Polish screening operations and hydrology snapping use EPSG:2180 projected grid metres internally. A degree is never treated as a metre. Projected distances and model outputs are not survey-certified ground measurements.

Preserve coordinate precision in saved results. Decimal places do not establish source accuracy. `requestedPoint` records the submitted location; `outlet.point` records the location selected by the hydrology model. Read `snapDistanceM` with both. Dataset, generation, row, and column identify a selected native cell; rounded geographic coordinates are not an exact replacement for that identity.

### Projected source data

Drawing APIs accept explicitly declared EPSG:2180, EPSG:4326 and EPSG:3857. EPSG:2180 positions are [easting,northing] metres: survey X=678465.20, Y=469232.50 becomes [469232.5,678465.2]. See the [drawing workflow](https://tarvena.pl/docs/skills/map-drawings.md). Retain the original CRS and labelled source coordinates with the source material. For EPSG:2180 input, distinguish easting and northing explicitly. Avoid an unlabelled `x, y` pair: authority axis order and common GIS library conventions can differ.

Geometry actions can carry an explicitly named projection. This does not change the geographic REST APIs' GeoJSON convention. Source land-cover labels and coordinate provenance describe source facts; calculation assumptions remain separately identified.

## BDOT10k roads

Use the read-only action `maps/roads/query` with a WGS84 `bbox`, output `projection` (`EPSG:2180` by default or `EPSG:4326`) and optional `limit` (1–2000, default 1000). Account map authorization applies. It queries the existing installed `OT_SKDR_L` archive without downloading a new dataset. Results contain tile-clipped road fragments and archived classification attributes, plus the source dataset, its publisher (GUGiK) and the source zoom. Full original BDOT attributes are not present in this archive. Limits and request examples are in the [road drainage example](catchments.md#draw-the-drained-strip).
