# Show a map

> Canonical URL: https://docs.mountaya.com/en/sdks/dart/map/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Render a Mountaya map in Flutter with MapEngine and MapView, draw an itinerary, move the camera, and respond to taps, refusals, the readout and waypoints.

`MapEngine` holds what the map shows, and `MapView` draws it with MapLibre. Your `State` makes the engine, hands it to the view, and closes it.

## Render the map

```dart
import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';

class TrailMap extends StatefulWidget {
  const TrailMap({super.key, required this.mountaya});

  final Mountaya mountaya;

  @override
  State<TrailMap> createState() => _TrailMapState();
}

class _TrailMapState extends State<TrailMap> {
  late final MapEngine map = MapEngine(widget.mountaya);

  @override
  void initState() {
    super.initState();
    unawaited(map.setTerrain());
  }

  @override
  void dispose() {
    map.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => MapView(engine: map);
}
```

`setTerrain()` shows the Tile API's first terrain. Every request the map makes carries your client's credential.

- `MapEngine(Mountaya client, {Uri? style, TerrainVariant terrainVariant = light, CameraPose camera, Language? labelLanguage, MapPaint? paint, GlyphSet glyphs = GlyphSet.marker, Geolocation? geolocation, List<MapRequestRule> requestRules = const []})`. It names no Flutter or MapLibre type, so it runs and is tested on Flutter's host runner, and every command has its effect before it returns.
- `MapView({required MapEngine engine, void Function(MapLibreMapController)? onReady, void Function(MapTap)? onTap, void Function(CameraPose)? onCameraChanged, bool readout = true})`. The view never closes the engine it is handed: Dart has no deinitializer, so the `State` that made it closes it in `dispose`.
- `MapEngine` refuses, with `ConfigurationException` where you make it, a client whose session token is `.function(...)` or whose credential is a secret key: the map hands its request hook headers as values set between requests. A `.value(...)` token, a `SessionTokenEngine` and a share token are taken.
- `setTerrain([slug])` shows the first terrain of the catalogue or the one named, in the variant `setTerrainVariant` asks for, light until you ask for dark. `setStyle(uri)` shows a style of your own. Everything drawn is drawn again on the base map a switch brings in, a layer you added included.
- The labels speak `labelLanguage:` (or `setLabelLanguage`), else the client's `language`, else the device reader's first language, else English. The map's own requests still carry the client's `Accept-Language`.
- Your own headers for your own hosts go in `requestRules`: `MapRequestRule(pattern: RegExp(r'^https://tiles\.example\.com/'), headers: {...})`. A rule is applied on the platform's side, after the client's headers, and never rewrites an address; write its pattern in the syntax Dart's, Java's and ICU's regular expressions share. Never set `maplibre_gl`'s `setHttpHeaders` or request limits: they take the request hook off.
- Two maps on one Tile API origin send the credential of the map shown last; a map showing a shared resource beside another map on the same origin puts `share_token` in its tile URLs.

## Draw an itinerary

```dart
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';
import 'package:mountaya_geo/mountaya_geo.dart';

// Your State calls it from initState, on the engine it holds.
Future<void> showTour(MapEngine map) async {
  await map.setTerrain();
  // The camera frames the itinerary once it is drawn; a later call takes its place.
  await map.setItinerary(
    '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
    fit: const CameraFit(padding: PixelPadding.all(48)),
  );
  // Your zones, each at the rank its source layer declares.
  await map.setZones(shown: true);
}
```

- Each call draws in a slot of its own: `setItinerary(id)`, `setCollection(id)`, `setItineraries(shown:)` (every itinerary of your credential's scope), `setZones(shown:)`, and `setSpecification(specification, name)` for a Tile API specification you hold. The latest call for a slot draws: one that answers after a later call answers `false`. `signal:` withdraws a call, which gives its slot back to the call it superseded. `clearItinerary()`, `clearCollection()` and `clearSpecifications()` remove them.
- An itinerary's restricted stretches are striped in their kind's colour beside its line; `setAccessRestrictionsVisibility(visible: false)` hides them.
- Data API results are drawn under ids of their own: `addIsochrones(input)`, `addDirections`, `addPlaces`, `addMatrix`, `addSuggestions`, `setPointsOfInterest`, each with a `…Result` twin taking an answer you already hold; `edit…(id, patch:)` asks again, `removeAnalysis(id)` removes one.
- Your own sources and layers: `addSource(MapSource.geoJson(...))`, `addLayer(MapLayer(id:, type: tile_schema.TileLayerType.line, source:, rank: LayerRank.poi.rank + 2, paint: {...}))`, `editLayer(id, paint: MapPatch.of({...}))`, `removeLayer`, `removeSource`.
- `editLayer` with `MapPatch.of({'line-width': null})` CLEARS `line-width` in Dart: a member the patch states replaces the one held, `null` included, and a member it leaves out is kept. Swift and Kotlin keep the value on a `null` instead. `MapPatch()..unstate('line-width')` leaves a member out.
- Three geometry slots draw over everything: `GeometrySlot.preview`, `emphasis` and `highlight`, through `setGeometry(geometry, slot)` and `clearGeometry(slot)`.

## Move the camera

```dart
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';
import 'package:mountaya_geo/mountaya_geo.dart';

void frameChamonix(MapEngine map) {
  // A move states the members it changes; the bearing and the pitch are kept.
  map.ease(const CameraTarget(center: [6.8712, 45.9231], zoom: 12));
  // The box around Chamonix and Argentière: west, south, east, north.
  map.fitBounds(
    [6.80, 45.85, 7.00, 46.00],
    const CameraFit(padding: PixelPadding.all(48)),
  );
  map.resetNorth();
}
```

- `jump`, `ease` and `fly` each take a `CameraTarget` (`center`, `zoom`, `bearing`, `pitch`) stating only the members it changes. `fitBounds(bounds, [fit])` frames `[west, south, east, north]` on the canvas the map is drawn on, facing north at the highest zoom that fits the canvas less its padding, capped by `maxZoom`. `zoomIn`, `zoomOut` and `resetNorth` (which turns the pitch back to 0 too) step it. Each lands at once where the reader turned animations off.
- `setMaxBounds([6.80, 45.85, 7.00, 46.00])` holds what the screen shows within the box, `null` lifting it. `setZoomBounds(min:, max:)`: a limit left out is kept (`ZoomLimit.kept`), and `ZoomLimit.released` goes back to MapLibre Native's own 0 and 25.5. A refused box or range is a `MapException` (`maxBoundsRefused`, `zoomBoundsRefused`).
- `map.state.camera` is the `CameraPose` the map rests at. `project(position)` and `unproject(point)` convert between `[longitude, latitude]` and logical pixels.
- `locate()` frames the device's position at zoom 16 at most, and throws `MapException` with a `reason` (`GeolocationRefusal.denied`, `noApi`, `unavailable`) where there is no fix. It never asks for location access; an approximate location reads as `denied`.

## Respond to the user

`MapView` hands you each tap, and the camera each time it comes to rest:

```dart
import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';

class TrailMap extends StatefulWidget {
  const TrailMap({super.key, required this.mountaya});

  final Mountaya mountaya;

  @override
  State<TrailMap> createState() => _TrailMapState();
}

class _TrailMapState extends State<TrailMap> {
  late final MapEngine map = MapEngine(widget.mountaya);
  late final StreamSubscription<MapEvent> _events;
  String? _picked;

  @override
  void initState() {
    super.initState();
    // Every gesture, and the features each lands on, as a stream.
    _events = map.events().listen((event) {
      if (event case MapEventFeatureTap(:final features)) {
        setState(() => _picked = features.firstOrNull?.layer);
      }
    });
  }

  @override
  void dispose() {
    unawaited(_events.cancel());
    map.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Stack(
    children: [
      MapView(
        engine: map,
        onTap: (tap) => setState(() => _picked = tap.marker),
        // At rest only, after the reader moved it or you did.
        onCameraChanged: (camera) => debugPrint('zoom ${camera.zoom}'),
      ),
      if (_picked case final picked?) Text(picked),
    ],
  );
}
```

- Each `MapEvent` is a top-level class: `MapEventTap`, `MapEventLongTap`, `MapEventFeatureTap`, `MapEventFeatureHover`, `MapEventFailure`, `MapEventLayersChange`, `MapEventAccessRefused` and `MapEventAccessRestored`. Swift spells them as cases (`.tap`, `.longTap`, `.featureTap`); Kotlin says `Click` where Dart says `Tap` (`MapEvent.Click`, `LongClick`, `FeatureClick`).
- `MapView`'s callbacks: `onTap(MapTap)` (`position`, `point`, and `marker`, the id of the marker it fell on), which also shows that marker's label; `onCameraChanged(CameraPose)`, at rest only, never frame by frame; `onReady(MapLibreMapController)` once the first style is drawn, for what the view does not wrap (an app that uses it declares `maplibre_gl` too).
- A tap while a waypoint is placed places it instead. A right-click or long press is `MapEventLongTap` and opens the readout.
- A live map asks MapLibre for the features under a hovering pointer only while something listens to `events()`.
- `featuresAt(point)`, `itinerariesAt`, `poisAt` and `zonesAt` answer at once what the map read at the last tap or hover; `queryFeaturesAt(point)` reads the live map at any point and answers later. Each `QueriedFeature` carries `properties`, `geometry`, `layer` and `sourceLayer`, the map's own features only, never the base map's.
- `elevationAt(position)` asks the Data API for the ground's elevation.

## Hear what the map refuses

A refused key or a failed tile arrives on `events()`. Listen to it and print each:

```dart
import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';

class TrailMap extends StatefulWidget {
  const TrailMap({super.key, required this.mountaya});

  final Mountaya mountaya;

  @override
  State<TrailMap> createState() => _TrailMapState();
}

class _TrailMapState extends State<TrailMap> {
  late final MapEngine map = MapEngine(widget.mountaya);
  late final StreamSubscription<MapEvent> _errors;

  @override
  void initState() {
    super.initState();
    _errors = map.events().listen((event) {
      switch (event) {
        case MapEventAccessRefused(:final status, :final url):
          debugPrint('Refused ($status) at $url');
        case MapEventFailure(:final url, :final cause):
          debugPrint('Could not load $url: $cause');
      }
    });
  }

  @override
  void dispose() {
    unawaited(_errors.cancel());
    map.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => MapView(engine: map);
}
```

- `MapEventAccessRefused(status, url)`: a `401`, `402` or `403` on one of the map's own requests (style, tile, sprite, glyph, the layers catalogue), never also told as a failure. A refused tile of a source the map draws names that source, so a tile of it received ends the refusal, told once as `MapEventAccessRestored`. A refusal told to nobody starts none.
- `MapEventFailure(url, status, cause)`: any other failure, a request that reached no answer (offline) included, one event per request. The request hook reports once a frame at most.
- A base map whose style does not arrive, its request failing or thirty seconds passing, gives the map back the one shown.
- Where reading the client's credential throws (a cookie or session source failing), the map sends nothing to the Tile API until a read answers, and tells each request it held back as a `MapEventFailure` whose `cause` is what the read threw.
- `MapException` carries `kind` (a `MapExceptionKind`), `name` and, for a locate, `reason`. Kinds: `analysisNotFound`, `cancelled`, `closed`, `fixRefused`, `kindMismatch`, `layerNotFound`, `markerNotFound`, `maxBoundsRefused`, `noInput`, `numberRefused`, `overlayNotFound`, `positionRefused`, `terrainNotFound`, `typeRefused`, `zoomBoundsRefused`. The set is open, so a `switch` over a kind keeps a default. Its `message` says what to pass instead.
- A command handed something the map cannot take throws `MapException` and leaves the map as it was: `map.editMarker('refuge', color: '#e64980')` on a map holding no marker `refuge` throws one of kind `markerNotFound`.
- `map.state.isAccessRequired` holds while a refusal stands, so a notice raised on it comes down by itself.

## Read a point

A long press opens a readout of the point: what the map draws there, the terrain's altitude, slope and aspect, and the coordinates. Turn it off to show your own:

```dart
import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';

class TrailMap extends StatefulWidget {
  const TrailMap({super.key, required this.mountaya});

  final Mountaya mountaya;

  @override
  State<TrailMap> createState() => _TrailMapState();
}

class _TrailMapState extends State<TrailMap> {
  late final MapEngine map = MapEngine(widget.mountaya);
  late final StreamSubscription<MapEvent> _presses;
  double? _ground;

  @override
  void initState() {
    super.initState();
    // The press is still told, and the ground's elevation is a Data API call away.
    _presses = map.events().listen((event) async {
      if (event case MapEventLongTap(:final tap)) {
        final ground = await map.elevationAt(tap.position);
        if (mounted) setState(() => _ground = ground);
      }
    });
  }

  @override
  void dispose() {
    unawaited(_presses.cancel());
    map.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Stack(
    children: [
      MapView(engine: map, readout: false),
      if (_ground case final ground?) Text('${ground.round()} m'),
    ],
  );
}
```

- The readout card states the point of interest and the zone drawn there, the classic overlay's band and its moment, the terrain's altitude, slope and aspect read off the elevation tiles at zoom 13 and above, and the coordinates with a copy action (latitude then longitude, five places). Figures are in the SDK's default units in the reader's language, the aspect in whole degrees beside its direction (`123° · South-East`), the overlay's moment in the device's own time zone.
- It opens with its top-left corner at the point, flipped where it would leave the safe area, then moved clear of the watermark's frame. A camera move or a tap closes it. `map.state.readout` is the `MapReadout` it shows (`position`, `poi`, `zone`, `terrain`, `overlay`, `bandMin`, `bandMax`), `null` while closed.
- `MapView(readout: false)` turns the card off; the press is still told on `events()` as `MapEventLongTap`.

## Attribution and watermark

The map draws the Mountaya watermark in the top-left corner of its safe area, unless your organization holds white label. Keep your own widgets clear of it:

```dart
import 'package:flutter/widgets.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';
import 'package:mountaya_geo/mountaya_geo.dart';

class TrailMap extends StatefulWidget {
  const TrailMap({super.key, required this.mountaya});

  final Mountaya mountaya;

  @override
  State<TrailMap> createState() => _TrailMapState();
}

class _TrailMapState extends State<TrailMap> {
  late final MapEngine map = MapEngine(widget.mountaya);

  @override
  void dispose() {
    map.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Stack(
    children: [
      Positioned.fill(child: MapView(engine: map)),
      SafeArea(
        child: Padding(
          // Starts below the watermark's frame.
          padding: EdgeInsets.fromLTRB(12, watermarkClearance + 8, 12, 12),
          child: SearchControl(map: map),
        ),
      ),
    ],
  );
}
```

The credit button opens what the map credits. Each source's attribution is listed there.

- The watermark is drawn once the organization read answers that it holds no white label, fails, or waits one attempt's budget (35 seconds) with no answer, and at once where the client holds no publishable key; a later answer of white label takes it away. A press opens Mountaya's site in the reader's language. Nothing a map takes hides it: white label is the agreement's.
- `MapEngine.loadOrganization()` reads the organization once per publishable key and Map Studio API origin for every map of the process, through `postOrganizationLookup`; `map.organization` holds the answer and `map.organizationRead` the state: `waiting`, `answered`, `failed`, `timedOut`, `noKey`. A client holding no publishable key (a share token among them) reads none.
- The answer decides the watermark and nothing else: controls, units, language and base map are what your code states, never your organization's embed settings.
- The frame stands `watermarkInset` from the safe area's top-left corner on both axes, `watermarkWidth` wide and `watermarkHeight` tall, and `watermarkClearance` is how far below the safe area's top it ends: the four names every native Mountaya SDK publishes. `isWatermarkKeptClear(state.organizationRead, whiteLabel: state.organization?.white_label ?? false)` answers `true` exactly while the SDK keeps its own interface clear of the frame.
- The safe area is read from the view itself, so a full-bleed map shows the mark below the status bar, a notch or a cutout. The mark is drawn by the view over MapLibre's canvas: a snapshot taken through the `onReady` controller records the canvas without it.
- `map.credits` lists what the credit sheet shows: Mountaya's credit and each drawn source's, the style's or its TileJSON's.

## Place waypoints

A waypoint edit places a waypoint where the reader taps. Then save it with the Map Studio API:

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_client/rest_schema.dart' as rest_schema;
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';

const itineraryId = '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21';
const waypointId = '5f2b8c1e-7a4d-4e9b-b3c6-0d8e1f2a4b67';

// Each tap on MapView places the waypoint until the edit ends.
void moveWaypoint(MapEngine map) => map.beginWaypointEdit(waypointId);

// Ends the edit, and saves the waypoint where the reader placed it.
Future<void> saveWaypoint(MapEngine map, Mountaya mountaya) async {
  final position = map.endWaypointEdit()?.position;
  if (position == null) return;
  await mountaya.studio.itineraries.patchItineraryWaypoint(
    itinerary_id: itineraryId,
    waypoint_id: waypointId,
    body: rest_schema.WaypointUpdateParams(geojson: GeoJsonPoint(position)),
  );
}
```

- `beginWaypointEdit(waypointId, {position})` starts an edit; each tap on `MapView` places the waypoint, and a tap within 40 logical pixels of an active segment (`setActiveSegments(lines)`) places it on the line, `isSnapped` true. `endWaypointEdit()` answers the `WaypointEdit` (`waypointId`, `position`, `isSnapped`), or `null` where none ran. `map.state.waypointEdit` holds the edit in progress.
- A map drawn some other way hands `placeWaypoint` its own `ScreenProjection` (`point` from a position, `position` from a point).
- Markers: `addMarker(MapMarker(id:, position:, glyph:, label:, color:))`, `editMarker(id, ...)` (a member left out is kept), `removeMarker`, `clearMarkers`. Markers stand above everything the map draws. A pin is a disc in the marker's colour, the tokens' accent where it names none, with its glyph from the engine's glyph set.
- The editing widgets of the TypeScript SDK have no Flutter twin: the waypoint is saved through `mountaya.studio.itineraries.patchItineraryWaypoint` (or `postItineraryWaypoint` for a new one), which acts as a member: a token minted for `studio-embedded` with `user_id`.

## Next steps

- [Controls and panels](https://docs.mountaya.com/en/sdks/dart/controls.md): Zoom, layers, points of interest and units.
- [Search](https://docs.mountaya.com/en/sdks/dart/search.md): Places, itineraries and zones over the map.
