# Map overlays and tiles

> GeoMap markers with shapes, size and color fields, clustering with zoom or spider expansion and dragging, bubbles, data labels, curved routes with arrows, polygons, a generic XYZ tile layer with attribution, annotations and coordinate conversion.

Canonical: https://salmonui.dev/docs/data-visualization/geo-map-overlays

```tsx
import { GeoMap } from '@salmonui/charts/geo-map';
import '@salmonui/charts/geo-map/styles.css';

<GeoMap
  layers={[{ shapes, markers: { data: cities, labelField: 'name', shape: 'balloon', cluster: true }, routes: [{ points: [[55, -4], [36, 14]], arrows: 'end' }] }]}
  onMarkerClick={(ctx) => open(ctx.datum)}
/>;
```

Overlays belong to a layer and draw in screen space, so they keep their size
while the map zooms. Layers, projections, zoom, selection and keyboard
navigation are on the [GeoMap page](https://salmonui.dev/docs/data-visualization/geo-map).

## Markers

`layer.markers` is one group or an array of groups: `data` with
`latitudeField` / `longitudeField` (default `latitude` / `longitude`),
`shape` (`circle`, `rectangle`, `triangle`, `invertedTriangle`, `diamond`,
`pentagon`, `star`, `cross`, `verticalLine`, `horizontalLine`, `balloon`),
`size` or `sizeField` scaled into `sizeRange`, `color` or `colorField`, a
`labelField` for tooltips and the table, and `render(ctx)` for any React
content (an image, an icon). `onMarkerClick(ctx)` receives the row and its
coordinates.

`markers.cluster` groups markers that share a 48 px grid cell (`cell`
changes it) into a counted cluster; clusters are recomputed per zoom level,
so they split as you zoom in. Clicking a cluster calls
`onClusterClick` and zooms into it; `expand: 'spider'` fans its markers out
on a circle around it with connector lines instead (a click elsewhere or
Escape closes it), and `expand: 'none'` keeps the view.
`cluster.render(ctx)` draws custom cluster content.

`markers.draggable` lets people move the markers of a group. A
pointer drag moves the marker with a DOM transform (never React state) and
calls `onMarkerMove({ markerId, layerId, groupId, index, datum, latitude,
longitude }, event)` once on release; the marker data is yours, so apply the
move:

```tsx
const [pins, setPins] = useState(initialPins);

<GeoMap
  layers={[{ shapes, markers: { id: 'pins', data: pins, labelField: 'name', draggable: true } }]}
  onMarkerMove={(move) => setPins((list) => list.map((p, i) => (i === move.index ? { ...p, latitude: move.latitude, longitude: move.longitude } : p)))}
/>;
```

Each draggable marker also has a focusable handle (`role="button"` with the
role description "movable marker", named by `labelField`): the arrow keys
move it 8 px per press and report each step with `event.source ===
'keyboard'`, and Enter or Space clicks it.

## Bubbles and labels

- `layer.bubbles: { valueField, radius: [min, max], shape: 'circle' |
  'square', color, colorScale }` draws one bubble per shape at its centroid,
  its area proportional to the joined value; `onBubbleClick` reports it.
- `layer.labels` (`true` or `{ field, overflow, overlap, render }`) writes a
  label at each shape's centroid: `overflow: 'hide'` drops labels wider than
  their shape, `'trim'` shortens them with an ellipsis, `overlap: 'hide'`
  (default) drops labels that collide, and `render(ctx)` draws custom content.

## Routes and polygons

- `layer.routes: [{ points, curvature, arrows: 'start' | 'end' | 'both',
  lineStyle: 'solid' | 'dashed' | 'dotted', color, width }]`.
- `layer.polygons: [{ points, color, label }]` draw filled areas from
  `[latitude, longitude]` points.

## Tiles

`layer.tiles: { url, attribution, minZoom, maxZoom, subdomains }` adds an XYZ
raster layer under the vector layers. `url` is a template with
`{z}`, `{x}`, `{y}` and optional `{s}`; `attribution` is required and always
rendered, also on the server. Tiles load on the client only (a lazy chunk
after hydration), so server HTML holds the vector layers. Follow your tile
provider's usage policy; the OpenStreetMap Foundation servers forbid heavy
use.

There is no built-in Bing or Azure Maps provider and no key flow (see the
[GeoMap page](https://salmonui.dev/docs/data-visualization/geo-map#no-bundled-geo-data-or-tile-provider)):
build the provider URL, key included, in your application:

```tsx
<GeoMap
  zoom
  layers={[{
    shapes,
    tiles: {
      url: `https://tiles.example.com/{z}/{x}/{y}.png?key=${apiKey}`,
      attribution: <a href="https://tiles.example.com/terms">© Example Tiles</a>,
      maxZoom: 18,
    },
  }]}
/>;
```

### Live demo: Tile layer and draggable markers

Live demo: https://salmonui.dev/demos/data-visualization/geo-map-tiles-drag

A GeoMap with an XYZ tile layer and its required attribution under vector regions, plus delivery stops you drag with the pointer or move with the arrow keys, reported by onMarkerMove.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { GeoMap } from '@salmonui/charts/geo-map';
import { REGIONS } from '../../lib/geo-fixture';

// A self-contained "debug" tile server: every tile is an SVG data URL that
// prints its own {z}/{x}/{y}, so the demo needs no network or API key. A real
// application points `url` at its provider, e.g.
// 'https://tile.example.com/{z}/{x}/{y}.png', and shows that provider's attribution.
const TILE_SVG =
  '<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256">' +
  '<rect width="256" height="256" fill="#eef4f8" stroke="#b6c8d6" stroke-width="2"/>' +
  '<path d="M0 128H256M128 0V256" stroke="#d3e0ea" stroke-dasharray="6 6"/>' +
  '<text x="12" y="28" font-family="monospace" font-size="18" fill="#56708a">z{z} x{x} y{y}</text></svg>';
const TILE_URL = `data:image/svg+xml,${encodeURIComponent(TILE_SVG).replace(/%7B/g, '{').replace(/%7D/g, '}')}`;

const INITIAL_STOPS = [
  { name: 'Depot', latitude: 55, longitude: -4 },
  { name: 'Warehouse', latitude: 45, longitude: 6 },
  { name: 'Store', latitude: 36, longitude: 14 },
];

/** An XYZ tile layer under vector regions, with delivery stops you can drag or move with the arrow keys. */
export default function GeoMapTilesDragDemo() {
  const [stops, setStops] = useState(INITIAL_STOPS);
  const [last, setLast] = useState('none');
  return (
    <div className="demo-stack" style={{ maxInlineSize: 640 }}>
      <GeoMap
        title="Delivery stops"
        subtitle="Drag a stop, or Tab to it and use the arrow keys"
        zoom
        layers={[
          {
            shapes: REGIONS,
            getShapeStyle: () => ({ fill: 'transparent', stroke: '#2563eb' }),
            tiles: { url: TILE_URL, attribution: <span>Demo tiles drawn in the page</span>, minZoom: 1, maxZoom: 8 },
            markers: { id: 'stops', data: stops, labelField: 'name', shape: 'balloon', size: 18, draggable: true },
          },
        ]}
        onMarkerMove={(move) => {
          setStops((all) => all.map((s, i) => (i === move.index ? { ...s, latitude: move.latitude, longitude: move.longitude } : s)));
          setLast(`${stops[move.index]?.name ?? move.markerId} → ${move.latitude.toFixed(2)}, ${move.longitude.toFixed(2)}`);
        }}
      />
      <p className="demo-status" aria-live="polite">
        Moved: <code>{last}</code>
      </p>
      <Button variant="outline" type="button" onClick={() => setStops(INITIAL_STOPS)}>
        Reset stops
      </Button>
    </div>
  );
}
```

## Annotations and coordinates

- `annotations: [{ x, y, content, align: 'start' | 'center' | 'end' }]` place
  React content at drawing pixels or percentages.
- `api.toCoordinates({ x, y })` and `api.toPoint([lat, lon])` convert between
  drawing pixels and coordinates, and `onMapClick({ latitude, longitude })`
  reports the clicked position. `api.fitBounds(bounds | 'markers')`
  fits the view.

## Accessibility and events

Every marker is listed in the map's accessible table, named by its
`labelField`; draggable markers add one focusable handle each (see above).
Overlay events: `onMarkerClick(ctx)` and `onClusterClick(ctx)` with
the row or cluster members and coordinates, `onBubbleClick({ layerId, key,
value, datum })`, `onMarkerMove(move, { source, reason })` and
`onMapClick({ latitude, longitude })`. Types are in the
[API reference](https://salmonui.dev/docs/reference/charts/geo-map).

### Live demo: Markers, clusters, bubbles and routes

Live demo: https://salmonui.dev/demos/data-visualization/geo-map-markers

Balloon markers that cluster until you zoom in, bubbles sized by a data field, a curved route with an arrow, a polygon overlay, an annotation, map-click coordinates and a planar seat map.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { GeoMap } from '@salmonui/charts/geo-map';
import { CITIES, POPULATION, REGIONS, SEATS } from '../../lib/geo-fixture';

// Markers with clustering, bubbles, a route, a polygon and a planar seat map.
export default function GeoMapMarkersDemo() {
  const [clicked, setClicked] = useState('');
  return (
    <div style={{ display: 'grid', gap: 12, maxInlineSize: 640 }}>
      <GeoMap
        title="Cities"
        projection="winkelTripel"
        zoom
        layers={[
          {
            shapes: REGIONS,
            data: POPULATION,
            dataKey: 'region',
            bubbles: { valueField: 'population', radius: [4, 22] },
            getShapeStyle: (ctx) => (ctx.name === 'Central' ? { fill: '#c2410c' } : undefined),
            markers: { data: CITIES, labelField: 'name', shape: 'balloon', size: 16, cluster: true },
            routes: [{ points: [[55, -4], [45, 6], [36, 14]], curvature: 0.25, arrows: 'end', lineStyle: 'dashed' }],
            polygons: [{ points: [[50, 10], [47, 16], [42, 12]], color: '#9c27b0', label: 'Zone' }],
          },
        ]}
        annotations={[{ x: '50%', y: 30, content: <em>Route: Alpha to Delta</em> }]}
        tooltip
        onMapClick={(p) => setClicked(`${p.latitude.toFixed(2)}, ${p.longitude.toFixed(2)}`)}
      />
      <output>Clicked: {clicked || 'nothing yet'}</output>
      <GeoMap title="Seats" width={420} height={210} selection={{ multiple: true }} layers={[{ shapes: SEATS, geometry: 'planar', labels: true }]} />
    </div>
  );
}
```
