# Element Editor documentation > Every page of the Element Editor docs (https://elementeditor.dev/docs) in one file, in navigation order. Index: https://elementeditor.dev/llms.txt. Each page is also served on its own as markdown at its URL plus `.md`. # What is Element Editor *A drawing and editing layer that plugs into your map.* Element Editor is a map drawing and GeoJSON editing library for React: users draw, edit and attach data to shapes on MapLibre or Leaflet maps. --- ## The problem Adding geometry editing to a web application is harder than it looks. Maps use coordinate systems that differ between libraries and formats. Drawing interactions need to handle complex FSM states: mid-draw, snapped, dragging a vertex, transforming a selection. Features have geometry constraints — circles and rectangles don't exist as such in GeoJSON, routes follow road networks. And all of that geometry still needs to be persisted, validated, and paired with structured property data from your domain. Building this from scratch means months of work before your users can draw a single polygon. Element Editor solves it at the library level. --- ## The architecture Element is a *layer*, not a map. With an adapter the map is yours: the basemap tiles, the tile provider, the initial viewport, the zoom controls, the search box — you own all of it. (The drop-in owns the map for you and ships a small basemap picker; see below.) Element sits on top and handles everything related to drawing and editing: the drawing tools, the cursor interactions, vertex handles, transform controls, snapping, boolean operations, and feature state management. Think of it this way: the map is the canvas. Element is the brush set. This design means you can use Element alongside any other map code you already have. Features drawn in Element are delivered as standard GeoJSON, which you can layer with your own map overlays, send to your backend, or pipe into any other geospatial tooling without a translation step. --- ## Two paths **Drop-in (`@element-editor/react`):** You want a full map editor embedded in your application and don't want to assemble the pieces yourself. `@element-editor/react` is a self-contained `` component that owns its own MapLibre map (a Leaflet version lives at `@element-editor/react/leaflet`), its own UI, and its own state. It ships built-in basemaps and a picker. Drop it into a `
` with an explicit height and it works. Drawing tools, vertex editing, snapping, boolean operations, schema forms, data table, import/export — all included. **Adapter (you own the map):** You already have a Leaflet or MapLibre map in your application. You want to add Element's editing tools to it without replacing your map setup. `@element-editor/adapter-leaflet` and `@element-editor/adapter-maplibre` add the editing layer as components that plug into your existing map instance. Your map stays exactly as it is; Element attaches the interaction layer on top. If you want the full editor UI — toolbars, panels, modals — you can also install `@element-editor/ui` and position those components wherever your layout needs them. --- ## What Element is not With an adapter, Element does not create your map or choose its tiles (the MapLibre adapter's `BasemapControl` picker is opt-in). The toolbar's place search finds a place and can add it as a feature, and the Route tool calls a routing service only to produce a road-snapped `LineString`: Element shows no turn-by-turn instructions and doesn't replace your navigation layer. Every server it calls can be swapped or turned off in `config.network` ([Third-party services](https://elementeditor.dev/docs/guides/third-party-services.md)). Element is also not a data store. It delivers your feature data via callbacks; where that data goes is your concern. Element has no opinion about your backend, your database, or your state management library. This scope discipline is intentional. A library that tries to own the basemap, the routing, the geocoder, and the editor invariably makes poor decisions about all four. Element does one thing: it lets users draw and edit geographic features. --- ## Unique capabilities Most map editing libraries handle drawing and vertex editing. Element adds three capabilities that alternatives don't provide: **Schema-driven property forms.** Every feature carries a `schemaId` linking it to a named schema. A schema defines typed fields — text, number, select, date, boolean — with optional validation rules. When a user selects a feature, they see a form generated from the schema. When they fill in fields, the values travel with the GeoJSON in the `properties` object. This means your features carry structured, validated domain data alongside their geometry, not just a loose bag of properties. **Data table.** A spreadsheet-style view of all features and their properties, accessible at any time. Rows and map selection stay in sync: selecting a feature on the map highlights it in the table, and vice versa. Cells are editable inline. Columns come from the schema fields (one tab per schema, or all of them). **GeoJSON inspector.** A live view of the raw GeoJSON for the current feature collection. Users can inspect and edit it directly — useful for debugging, for power users who want to paste coordinates, and for developers building integrations who want to see exactly what the `onChange` callback will deliver. --- # Choosing a package *Three questions to find your starting point.* --- ## The decision ### Question 1: Do you already have a Leaflet or MapLibre map in your application? **No** — you don't have a map yet, or you want a fully self-contained editor without managing a map instance yourself. → Use **`@element-editor/react`**. It owns the map (MapLibre by default), the UI, and all editor state. You mount one component; everything else is handled for you. [Quick start →](https://elementeditor.dev/docs/quickstart/react.md) Prefer Leaflet for the drop-in? Import from `@element-editor/react/leaflet` instead (and install `@element-editor/adapter-leaflet leaflet react-leaflet`). Pick MapLibre unless you specifically need Leaflet: it has vector basemaps and a basemap picker with a theme-aware Auto option. Leaflet drop-in basemaps are raster only. See [Basemaps](https://elementeditor.dev/docs/guides/basemaps.md). **Yes** — you have an existing map and want to add editing tools to it. → Continue to Question 2. --- ### Question 2: Which map engine are you using? **Leaflet or react-leaflet** → Use **`@element-editor/adapter-leaflet`**. It plugs into an existing `MapContainer` via `ElementEditorControls`. [Quick start →](https://elementeditor.dev/docs/quickstart/adapter-leaflet.md) **MapLibre GL JS, MapTiler SDK, or Mapbox GL JS** → Use **`@element-editor/adapter-maplibre`**. It accepts any map instance from this family — all three share the same underlying API lineage. [Quick start →](https://elementeditor.dev/docs/quickstart/adapter-maplibre.md) --- ### Question 3: Do you need full control over the editor UI layout? `ElementEditorControls` renders no buttons of its own: it adds the editing layer to your map. The toolbars, panels and modals come from **`@element-editor/ui`**, and you place them yourself. **No** — you want the standard toolbar and panels. → Follow the adapter quick start. Its "Adding the full UI" section renders the standard set. **Yes** — you need toolbars, panels, and modals at specific positions in your layout, or integrated with your own UI components. → Place the `@element-editor/ui` components where you need them. See [The `@element-editor/ui` path](https://elementeditor.dev/docs/introduction/choosing-a-package.md#the-element-editorui-path) below and the [Custom UI with adapters guide](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md). --- ## Summary table | I want... | Package(s) | |---|---| | A full editor, no existing map | `@element-editor/react` (MapLibre) | | A full editor on Leaflet | `@element-editor/react/leaflet` (+ `adapter-leaflet`, `leaflet`, `react-leaflet`) | | Editing on my Leaflet map | `@element-editor/adapter-leaflet` | | Editing on my MapLibre GL map | `@element-editor/adapter-maplibre` | | Editing on my MapTiler SDK map | `@element-editor/adapter-maplibre` | | Editing on my Mapbox GL JS map | `@element-editor/adapter-maplibre` | | Full UI control (custom toolbar positions, layouts) | adapter + `@element-editor/ui` | --- ## The `@element-editor/ui` path When you use an adapter, Element Editor adds the editing interaction layer to your map but renders no visible UI. `@element-editor/ui` provides all the interface components — `FloatingToolbar`, `EditingToolbar`, `LayersPanel`, `DataTablePanel`, `SchemaModal`, `GeoJSONModal`, and more — as individual React components you can place anywhere in your layout. This means you can build the same full-editor experience as `@element-editor/react` while controlling exactly where each piece lives: a toolbar docked to your application's sidebar, a data table in a bottom panel, modals triggered from your own navigation. The adapter handles the map editing layer; `@element-editor/ui` provides the interface components; you decide the layout. The [Custom UI with adapters guide](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md) shows the complete provider stack and placement patterns for both Leaflet and MapLibre. --- > **Note:** `@element-editor/core` holds the shared TypeScript types (`FeatureCollection`, `GeoJSONFeature`, `Schema`, …) and is installed automatically with every Element package. `@element-editor/react` re-exports the common types; the adapters don't. With an adapter, add `@element-editor/core` to your `package.json` (same version as the adapter) and import the types from it: > > ```ts > import type { FeatureCollection } from '@element-editor/react' // with @element-editor/react > import type { FeatureCollection } from '@element-editor/core' // with an adapter > ``` --- # GeoJSON primer *Everything Element Editor needs you to know about the data format — and nothing more.* --- ## What GeoJSON is GeoJSON is an open standard (RFC 7946) for representing geographic features as JSON. An Element `FeatureCollection` is valid GeoJSON — you can take it anywhere: store it in a database, serve it from an API, load it in QGIS, or pass it to any other library that speaks GeoJSON. You don't need to construct GeoJSON by hand. Element's `onChange` callback gives you a valid `FeatureCollection` on every change. This primer exists so you understand what you're receiving — not because you need to produce it. --- ## Geometry types GeoJSON defines seven geometry types. Element's drawing tools create Points, LineStrings and Polygons, and merging creates the Multi* types. Imported data can use any of the seven, including MultiPoint and GeometryCollection. The common ones: ### Point A single location on the map. Coordinates are `[longitude, latitude]`. ```json { "type": "Point", "coordinates": [-0.1276, 51.5074] } ``` ### LineString An ordered sequence of two or more points. Represents paths, roads, routes, or any linear feature. ```json { "type": "LineString", "coordinates": [ [-0.1276, 51.5074], [-0.0994, 51.5142], [-0.0753, 51.5084] ] } ``` ### Polygon A closed shape. The first element in `coordinates` is the **outer ring** — a sequence of positions that closes back on itself (the first and last position must be identical). Additional elements are **inner rings** representing holes cut out of the polygon. ```json { "type": "Polygon", "coordinates": [ [ [2.294, 48.858], [2.296, 48.858], [2.296, 48.860], [2.294, 48.860], [2.294, 48.858] ] ] } ``` A polygon with a hole adds a second ring: ```json { "type": "Polygon", "coordinates": [ [[...outer ring...]], [[...inner hole ring...]] ] } ``` ### MultiPolygon An array of Polygons. Used for features that are geographically discontinuous — a country with islands, a state with an exclave, a postal district split across a river. ```json { "type": "MultiPolygon", "coordinates": [ [[[...ring of polygon 1...]]], [[[...ring of polygon 2...]]] ] } ``` ### MultiLineString An array of LineStrings. Used for road networks, river systems, or any feature composed of multiple distinct linear segments. ```json { "type": "MultiLineString", "coordinates": [ [[...line 1 coordinates...]], [[...line 2 coordinates...]] ] } ``` --- ## Feature A geometry on its own is just a shape — no identity, no data. A **Feature** wraps a geometry with an `id` and a `properties` object that holds the feature's attributes. ```json { "type": "Feature", "id": "3f2a1c9b-...", "geometry": { "type": "Point", "coordinates": [-0.1276, 51.5074] }, "properties": { "name": "Trafalgar Square", "category": "landmark", "capacity": 10000 } } ``` The `properties` object can hold anything. When you define a schema in Element, the property names are the field `key`s from your schema definition. --- ## FeatureCollection A **FeatureCollection** is an array of Features. This is the top-level object Element's `onChange` callback gives you on every change. ```json { "type": "FeatureCollection", "features": [ { "type": "Feature", "id": "...", "geometry": { ... }, "properties": { ... } }, { "type": "Feature", "id": "...", "geometry": { ... }, "properties": { ... } } ] } ``` --- ## The coordinate order trap GeoJSON coordinates are `[longitude, latitude]` — mathematically sensible (x before y), but the opposite of how English speakers say "latitude and longitude." If you've been writing map code for any length of time, you have already been bitten by this at least once. Element handles the conversion at every map boundary so you never flip coordinates yourself. But if you inspect raw coordinates and the numbers look backwards, that's why. --- ## What Element adds to GeoJSON Standard GeoJSON has no concept of schemas, groups, or drawing tool history. Element extends the format with a few foreign members, all within the rules of RFC 7946: `metadata` on the collection, and `schemaId`, `groupId`, `hidden` and `_drawType` on features. ### `metadata` on FeatureCollection Element adds a `metadata` envelope to the root `FeatureCollection` object. This is where schema definitions and feature groups travel with the data — so when you export and re-import a file, the full editor state is preserved. ```json { "type": "FeatureCollection", "metadata": { "schemas": [ { "id": "location", "name": "Location", "fields": [ { "key": "name", "label": "Name", "type": "text", "required": true }, { "key": "category", "label": "Category", "type": "select", "required": false, "options": ["park", "hospital", "school"] } ] } ], "groups": [] }, "features": [...] } ``` ### `_drawType` on features When a user draws a circle, rectangle, or route, GeoJSON has no way to record that intent — a circle is stored as a Polygon; a rectangle is stored as a Polygon; a route is stored as a LineString. Element adds a `_drawType` foreign member to those features so it can recover the original intent. RFC 7946 §6.1 explicitly permits extension members on Feature objects. Element uses the underscore prefix convention to signal that these are application-specific extensions. ```json { "type": "Feature", "id": "...", "geometry": { "type": "Polygon", "coordinates": [...] }, "properties": {}, "_drawType": "circle" } ``` Possible values: `"circle"`, `"rectangle"`, `"route"`. ### `_waypoints` on route features Route features carry an additional `_waypoints` field in `properties` — the original click points the user placed when drawing the route. These are the input coordinates sent to the routing API; Element records them but doesn't re-route from them. Editing the route's points, or simplifying, smoothing or buffering it, makes it a plain line: `_drawType` and `_waypoints` are both removed. > **Warning:** Do not strip `_drawType` when round-tripping feature data through your backend. Element uses it to tell users what an edit will do: entering vertex edit on a circle or rectangle says the first point change turns it into a plain polygon (a route: a plain line), and Simplify / Smooth note when a circle or rectangle will lose its tag. The first point change, or a geometry operation (buffer, simplify, smooth, boolean ops), removes the tag; moving, rotating or scaling with the transform box keeps it. Strip it and Element treats the shape as a plain polygon or line. --- > **Tip:** When you export a FeatureCollection from Element (via the export button or `ref.current.exportAs('geojson')`), the result is fully valid RFC 7946. Any tool, database, or API that accepts GeoJSON will accept it. The `metadata` and `_drawType` fields are ignored by tools that don't know about them. --- # Quick start: @element-editor/react *A complete map editor in your React app — no map setup required. Estimated time: ~5 minutes.* `@element-editor/react` is the self-contained package. It owns its own MapLibre map and brings everything: built-in basemaps with a picker, drawing tools, sidebar, data table, import/export, and keyboard shortcuts. Drop it in, give it a container, wire up `onChange`. > **Configure visually first?** [Open the playground](https://elementeditor.dev/playground) — tweak every setting in a sidebar, watch the editor update live, copy the resulting `` snippet straight into your app. --- ## Step 1 — Install ```bash npm install @element-editor/react maplibre-gl ``` `@element-editor/react` is built on MapLibre GL JS. Install `maplibre-gl` next to it: it is marked as an optional peer dependency only so that Leaflet-only apps can skip it, but the default entry needs it. You also need React. | Package | Supported versions | |---|---| | `react` | `^19.2` | | `react-dom` | `^19.2` | | `maplibre-gl` | 5.5 or 6 | React 18 is not supported. If your app is on an older React 19, upgrade it first; npm otherwise stops with a peer dependency conflict (`ERESOLVE`). Apps made with Next.js 15's `create-next-app` pin React 19.1: ```bash npm install react@^19.2 react-dom@^19.2 ``` --- ## Step 2 — Import the CSS Add this import once, near your app entry point (`main.tsx`, `App.tsx`, or your global CSS file): ```tsx import '@element-editor/react/style.css' ``` > **Warning:** If you skip this import, the map renders without its controls and panels are unstyled. The stylesheet bundles `maplibre-gl.css`, so you don't need to import that yourself. The stylesheet only styles the editor. It doesn't reset your page's headings, buttons or other elements. It is plain CSS, so the import works in any setup: Vite, webpack, Next.js, with or without Tailwind (including Tailwind v3), or a CSS `@import`. It contains no `@layer`, `@tailwind` or `@apply` directives for your build to reinterpret, and every Element Editor rule (utilities included) only matches inside the editor (the element with `data-elm-theme` and Element's portals), so it can't override your own classes elsewhere on the page, even ones with the same names (`hidden`, `absolute`, `md:flex`, …). The bundled map library CSS (`.maplibregl-*`, or `.leaflet-*` in the Leaflet stylesheet) stays global, as when you import it yourself. --- ## Step 3 — Add the component The component fills its container. The parent element needs an explicit height. (In Next.js or any SSR framework, render it client-only; see [Using Element with Next.js](https://elementeditor.dev/docs/guides/nextjs.md).) ```tsx import { ElementEditor } from '@element-editor/react' import '@element-editor/react/style.css' export default function App() { return (
console.log(data)} />
) } ``` That's it. You now have a working map editor: drawing tools (point, line, area, rectangle, circle, freehand, route, and a picker that imports shapes from OpenStreetMap), vertex editing, transform, snapping, boolean operations, schema-driven property forms, a spreadsheet-style data table, a two-way GeoJSON inspector, 25-step undo/redo, and keyboard shortcuts. Every drawing tool is keyed: `P` point, `L` line, `G` area, `R` rectangle, `O` circle, `F` freehand, `C` route, `X` picker, `M` measure. Other shortcuts include `T` (data table), `A` (transform), `S` (schema), `I` (GeoJSON) and `/` (layers panel). Press `K` to see the full list. --- ## Step 4 — Wire up data persistence `onChange` fires after every committed change and delivers the full `FeatureCollection`. Connect it to wherever you store data: ```tsx import { ElementEditor } from '@element-editor/react' import type { FeatureCollection } from '@element-editor/react' import '@element-editor/react/style.css' export default function App() { function handleChange(data: FeatureCollection) { // data is a valid GeoJSON FeatureCollection. // Send it to your API, store it in state, or write it to localStorage. localStorage.setItem('my-map', JSON.stringify(data)) } return (
) } ``` --- ## Common variations ### Loading existing data Pass a GeoJSON `FeatureCollection` to `initialData`. It is the starting data: applied on mount (or, if it is still `null` then, once when it arrives, as long as the user hasn't edited), without an undo step and without firing `onChange`. Later changes to the prop are ignored; replace the data with `ref.setFeatureCollection()`. ```tsx import { ElementEditor } from '@element-editor/react' const savedData = JSON.parse(localStorage.getItem('my-map') ?? 'null') localStorage.setItem('my-map', JSON.stringify(data))} /> ``` ### Where the map starts On a first visit the map fits `initialData`; after that it reopens where the user left it. Set `initialView` to choose yourself, `mapOptions` for extra map options and `onMapReady` to add your own layers once the map exists: ```tsx import { ElementEditor } from '@element-editor/react' { map.addSource('districts', { type: 'geojson', data: '/districts.geojson' }) map.addLayer({ id: 'districts', type: 'line', source: 'districts' }) }} /> ``` See [Setting up the map](https://elementeditor.dev/docs/reference/element-editor-react.md#setting-up-the-map). ### Restricting which tools are available Pass a `tools` array. Only the listed tools appear in the toolbar, and keyboard shortcuts for the others are suppressed. ```tsx import { ElementEditor } from '@element-editor/react' console.log(data)} /> ``` The tool names (`DrawTool`; `'polygon'` is the **Area** tool): ```ts type DrawTool = | 'polygon' | 'rectangle' | 'circle' | 'line' | 'point' | 'freehand' | 'route' | 'picker' | 'measure' | 'search' ``` Everything you don't list is hidden, including the picker, measure and the search box (see [Restricting tools](https://elementeditor.dev/docs/guides/restricting-tools.md)). ### Read-only mode `readonly` disables all drawing and editing. Features remain visible and selectable — useful for displaying saved data without allowing modifications. ```tsx import { ElementEditor } from '@element-editor/react' const savedData = JSON.parse(localStorage.getItem('my-map') ?? 'null') ``` ### Layout `layout` chooses how the panels arrange around the map. ```tsx import { ElementEditor } from '@element-editor/react' // default — sidebar docked on the right // edit form opens in a modal on selection // data table and layers panel side by side in a bottom panel ``` ### Basemaps The default basemap is `'auto'`: light Streets in a light editor, Dark in a dark editor. A picker in the bottom-left corner lets users switch between Streets, Terrain, Light, Dark and OpenStreetMap, and their choice is remembered. ```tsx import { ElementEditor } from '@element-editor/react' // starting basemap // no picker ``` See the [Basemaps guide](https://elementeditor.dev/docs/guides/basemaps.md) for custom styles and self-hosting. ### Moving a control Every button has a place in `config.ui.layout`. `withLayout` moves or hides a few and keeps the rest of the default layout: ```tsx import { ElementEditor, withLayout } from '@element-editor/react' ``` See [Configuring layout](https://elementeditor.dev/docs/guides/configuring-layout.md). ### Going to production Out of the box the editor uses free public services: OpenFreeMap and Mapterhorn for basemaps, Overpass for the picker, the OSRM demo server for the Route tool (car-only, not for production) and Nominatim for search. Point them at your own servers or keys with `config.network`, and send failures to your error tracking with `onError`: ```tsx import { ElementEditor } from '@element-editor/react' console.error(e.code, e.source, e.message)} /> ``` See [Third-party services and self-hosting](https://elementeditor.dev/docs/guides/third-party-services.md) and [`onError`](https://elementeditor.dev/docs/reference/events.md#onerror). ### Leaflet drop-in Prefer Leaflet? The same component is available from `@element-editor/react/leaflet`. Its peers are optional, so install them yourself (no `maplibre-gl` needed): ```bash npm install @element-editor/react @element-editor/adapter-leaflet leaflet react-leaflet npm install -D @types/leaflet # TypeScript: leaflet ships no types of its own ``` ```tsx import { ElementEditor } from '@element-editor/react/leaflet' import '@element-editor/react/leaflet/style.css' // includes Leaflet's CSS ``` The API is the same, except that `tileLayer` and `renderer` are Leaflet-only and basemaps are raster-only (an optional `basemaps` list). Both entries share the same types (`import type { FeatureCollection } from '@element-editor/react'` works for either). ### Using the ref API If you need to trigger actions imperatively — saving on a button click, flying to a location, or exporting a file — attach a ref: ```tsx import { useRef } from 'react' import { ElementEditor } from '@element-editor/react' import type { ElementEditorRef } from '@element-editor/react' export default function App() { const ref = useRef(null) function handleSave() { const data = ref.current?.getFeatureCollection() if (data) localStorage.setItem('my-map', JSON.stringify(data)) // or send it to your API } function addHome() { const f = ref.current?.addFeature({ type: 'Feature', geometry: { type: 'Point', coordinates: [2.35, 48.86] }, properties: { name: 'Home' } }) if (f) ref.current?.select([f.id], { fit: true }) } return ( <>
) } ``` The `ElementEditorRef` interface (see the [reference](https://elementeditor.dev/docs/reference/element-editor-react.md#elementeditorref) for details): ```ts interface ElementEditorRef { getFeatureCollection: () => FeatureCollection // current data as an object setFeatureCollection: (data: FeatureCollectionInput) => void // replace the dataset exportGeoJSON: () => string // current data as GeoJSON text exportAs: (format: 'geojson') => void // trigger a file download importGeoJSON: (raw: unknown, mode?: 'replace' | 'merge') => ImportResult addFeature: (feature: GeoJSONFeatureInput, options?) => GeoJSONFeature | null // the stored feature (with id), or null updateFeature: (id: string, patch: FeaturePatch, options?) => boolean updateFeatures: (updates: { id: string; patch: FeaturePatch }[], options?) => void // one commit, one undo step removeFeatures: (ids: string[], options?) => number // how many were removed getSelection: () => string[] select: (ids: string[], options?: { fit?: boolean }) => void // fit: zoom to the selection setTool: (tool: DrawTool | null) => boolean // null exits; false if unavailable setVertexEdit: (id: string | null) => boolean // edit a line's / area's points; null leaves getMap: () => maplibregl.Map | null // L.Map on /leaflet; null until mounted getBasemap: () => BasemapInput // the current basemap choice setBasemap: (basemap: BasemapInput) => void // switch like a user pick flyTo: (options: { center: [number, number]; zoom?: number }) => void // center is [lng, lat] setZoom: (zoom: number) => boolean // false if the map isn't ready fitBounds: (target: [number, number][] | [number, number, number, number]) => void submit: () => boolean // validate, then onSubmit or onValidationError undo: () => void redo: () => void clearSelection: () => void } ``` Use `importGeoJSON` to swap datasets at runtime without remounting the editor (which would reset zoom, selection, and undo history). `mode` defaults to `'replace'`; pass `'merge'` to append. `submit()` runs validation and either calls `onSubmit` with a clean FeatureCollection or fires `onValidationError`. --- ## What's next - [Component reference](https://elementeditor.dev/docs/reference/element-editor-react.md) — every prop, event, and ref method documented - [Events guide](https://elementeditor.dev/docs/reference/events.md) — when to use `onChange` vs granular events vs the ref API - [Theming](https://elementeditor.dev/docs/guides/theming.md) — match the editor to your product's visual identity - [Persisting data](https://elementeditor.dev/docs/guides/persisting-data.md) — patterns for localStorage, REST APIs, and real-time sync - [Restricting tools](https://elementeditor.dev/docs/guides/restricting-tools.md) — control the full editor surface, including `maxFeatures` and `readonly` --- # Quick start: Leaflet adapter *Add Element Editor drawing tools to your existing Leaflet map. Estimated time: ~10 minutes.* Use `@element-editor/adapter-leaflet` when you already have a Leaflet or react-leaflet map in your application and want to add editing to it — without replacing your map setup. Element attaches as an editing layer; your map, tile provider, and controls stay exactly as they are. > **Configure visually first?** [Open the playground](https://elementeditor.dev/playground) to tweak every setting and copy the resulting config. Pass the same `config` object to ``. --- ## Step 1 — Install ```bash npm install @element-editor/adapter-leaflet @element-editor/ui leaflet react-leaflet npm install -D @types/leaflet # TypeScript: leaflet ships no types of its own ``` If `leaflet` and `react-leaflet` are already in your project, you don't need to reinstall them. Peer dependencies: `react` and `react-dom` `^19.2`, `react-leaflet` `^5`, `leaflet` `^1.9`. React 18 is not supported. If your app is on an older React 19, upgrade it first; npm otherwise stops with a peer dependency conflict (`ERESOLVE`). Apps made with Next.js 15's `create-next-app` pin React 19.1: ```bash npm install react@^19.2 react-dom@^19.2 ``` `@element-editor/ui` provides the toolbars and panels. The adapter already depends on it, but list it in your own `package.json` so you can import from it (pnpm and other strict package managers only resolve packages you declare). The same applies to `@element-editor/core` if you want its types and helpers, such as `FeatureCollection` or `getFeatureCollectionBBox`. Keep all `@element-editor/*` packages on the same version. --- ## Step 2 — Import the CSS Add this import once, near your app entry point: ```tsx import '@element-editor/adapter-leaflet/style.css' ``` The stylesheet includes Leaflet's CSS (`leaflet/dist/leaflet.css`), so you don't need to import that separately. Importing it again is harmless. > **Warning:** The JavaScript entry doesn't import any CSS. Without this import, tiles vanish, markers disappear, and the editor UI is unstyled. The stylesheet doesn't reset your page. Tailwind's base styles apply only inside an element with a `data-elm-theme` attribute, so all editor UI must be rendered inside one (Step 3 shows how). The stylesheet is plain CSS, so the import works in any CSS setup: Vite, webpack, Next.js, with or without Tailwind (including Tailwind v3), or a CSS `@import`. It has no `@layer`, `@tailwind` or `@apply` directives for your build to reinterpret, and every Element rule (utilities included) only matches inside the `data-elm-theme` element and Element's portals, so it can't override your own classes elsewhere on the page, even ones with the same names (`hidden`, `absolute`, `md:flex`, …). Leaflet's own CSS stays global, as when you import `leaflet.css` yourself. Editor UI you render in a container of your own outside that element (a sidebar, your own portal) gets no Element styles: give that container a `data-elm-theme` attribute too (or `data-elm-portal` for a portal). --- ## Step 3 — Build the component Wrap your map in `ElementEditorUIProvider` and `GeoStoreProvider`, put it inside a `data-elm-theme` element, then place `ElementEditorControls` inside the `MapContainer` alongside your existing layers: ```tsx import { MapContainer, TileLayer } from 'react-leaflet' import { ElementEditorUIProvider, GeoStoreProvider, ElementEditorControls } from '@element-editor/adapter-leaflet' import '@element-editor/adapter-leaflet/style.css' export default function MyMap() { return (
console.log(data)} />
) } ``` > **Note:** Placement rules: > - `ElementEditorUIProvider` provides the contexts the editor needs: an error boundary, config, keyboard shortcuts, events and toasts, and the map controller used by zoom-to actions. `ElementEditorControls` throws without it. It also renders Element's own toast ``, so you don't need to add one. > - `GeoStoreProvider` must wrap `MapContainer` (or any ancestor of it). It creates the store that `ElementEditorControls` and any `@element-editor/ui` components share. Use one per editor. > - The `data-elm-theme` element (`"light"` or `"dark"`) scopes the editor's styles and its keyboard shortcuts: a key press only acts on this editor when focus or your last click is inside it. > - `ElementEditorControls` must be a **child of `MapContainer`**. It uses `useMap()` from react-leaflet internally. --- ## What you get Your existing Leaflet map now has Element editing attached: - Drawing tools for areas, lines, points, rectangles, circles, freehand paths, and routes — plus a picker (`X`) that imports shapes from OpenStreetMap - Drag-to-draw rectangles and circles; spacebar pans during drawing without leaving the tool; `⌘ J` keeps the tool active after a shape commits - Click-to-select, multi-select, box-select; right-click context menu on features - Vertex editing, transform (scale/rotate), boolean operations, simplify/smooth/buffer - Group / ungroup with `⌘ G` / `⌘ ⇧ G`; groups carry through to `metadata.groups` - 25-step undo/redo - `onChange` fires after every committed change with the full `FeatureCollection` `ElementEditorControls` renders no visible UI by default — it attaches invisible interaction overlays to the map. To add toolbars and panels, see [Adding the full UI](https://elementeditor.dev/docs/quickstart/adapter-leaflet.md#adding-the-full-ui) below. --- ## Step 4 — Wire up data `onChange` delivers a complete GeoJSON `FeatureCollection` after each committed change. Load existing data with `initialData`. The types come from `@element-editor/core` (see Step 1): ```tsx import { MapContainer, TileLayer } from 'react-leaflet' import { ElementEditorUIProvider, GeoStoreProvider, ElementEditorControls } from '@element-editor/adapter-leaflet' import type { FeatureCollection } from '@element-editor/core' import '@element-editor/adapter-leaflet/style.css' export default function MyMap() { const savedData: FeatureCollection | null = JSON.parse(localStorage.getItem('my-map') ?? 'null') function handleChange(data: FeatureCollection) { localStorage.setItem('my-map', JSON.stringify(data)) } return (
) } ``` If `initialData` isn't a valid `FeatureCollection`, the editor reports an `error` event and starts empty instead of crashing. A single `Feature` is wrapped in a collection. --- ## Adding the full UI `ElementEditorControls` handles the editing layer. The toolbars, sidebar, data table, and modals are separate `@element-editor/ui` components that you position in your own layout. > **Tip:** With the full UI stack you get exactly the same experience as `@element-editor/react` — but with full control over where each panel lives in your layout. UI components go **outside** `MapContainer`, positioned absolutely over the map div, and inside the same `data-elm-theme` element. They share the same `GeoStoreProvider` store as `ElementEditorControls`. `FloatingToolbar`, `LayersPanel` and `DataTablePanel` position themselves over the map, against the `data-elm-theme` element (give it `position: relative`). `EditingToolbar`, `ActiveDrawingToolbar` and single buttons such as `FitBoundsButton` render in place, so put them in an absolutely positioned wrapper of your own, as below. `DataTablePanel` writes its open height to `--elm-table-offset` on the `data-elm-theme` element; add it to a bottom-anchored wrapper's `bottom` and the wrapper rides above the open table. The data table and the modals are lazy-loaded, so they must be wrapped in ``. Give each its own boundary: a shared one unmounts the already-loaded siblings while a new one loads. ```tsx import { Suspense, useState } from 'react' import { MapContainer, TileLayer } from 'react-leaflet' import { ElementEditorUIProvider, GeoStoreProvider, ElementEditorControls } from '@element-editor/adapter-leaflet' import { ThemeContext, FloatingToolbar, EditingToolbar, ActiveDrawingToolbar, FitBoundsButton, LayersPanel, DataTablePanel, ShortcutsModal, SettingsModal, SchemaModal, GeoJSONModal, useUIStore, } from '@element-editor/ui' import '@element-editor/adapter-leaflet/style.css' // Schema and GeoJSON modals render whenever mounted, so mount them only while open. function ConditionalModals() { const schemaOpen = useUIStore((s) => s.schemaModalOpen) const toggleSchema = useUIStore((s) => s.toggleSchemaModal) const codeOpen = useUIStore((s) => s.codeModalOpen) const toggleCode = useUIStore((s) => s.toggleCodeModal) return ( <> {schemaOpen && } {codeOpen && } ) } export default function MyMap() { const [mapReady, setMapReady] = useState(false) return (
{/* Map — fills the container */} setMapReady(true)} > {mapReady && console.log(data)} />} {/* UI panels — outside MapContainer, positioned absolutely over the map */} {mapReady && ( <> {/* Drawing tool selector: positions itself, top center */} {/* Edit actions and finish / cancel drawing: you place these (bottom center here) */}
{/* Fly to fit all features: you place it (bottom left here) */}
{/* Feature list sidebar: positions itself, right */} {/* Spreadsheet view */} )}
) } ``` `ThemeContext` tells portaled UI (tooltips, menus, modals) which theme to use. Keep its value in sync with `data-elm-theme`. Any UI you portal elsewhere yourself should carry a `data-elm-portal` attribute on its root, so Element styles it and keyboard shortcuts keep working while it has focus. For a complete working example with buttons that open each panel, see [Custom UI with adapters](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md). --- ## What's next - [Adapter reference](https://elementeditor.dev/docs/reference/adapter-leaflet.md) — every prop, event, and ref method for `ElementEditorControls` - [Custom UI with adapters](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md) — build the full editor experience with `@element-editor/ui` - [Persisting data](https://elementeditor.dev/docs/guides/persisting-data.md) — localStorage, REST APIs, granular events, and the ref API --- # Quick start: MapLibre adapter *Add Element Editor drawing tools to your existing MapLibre GL, MapTiler SDK, or Mapbox GL JS map. Estimated time: ~10 minutes.* Use `@element-editor/adapter-maplibre` when you already have a MapLibre GL (or compatible) map in your application. Element attaches as an editing layer over your existing map instance — your basemap, style, camera controls, and custom layers are untouched. This adapter also works with **MapTiler SDK** (which extends MapLibre GL directly) and **Mapbox GL JS** (same runtime API surface). See [Using with MapTiler SDK](https://elementeditor.dev/docs/quickstart/adapter-maplibre.md#using-with-maptiler-sdk) and [Using with Mapbox GL JS](https://elementeditor.dev/docs/quickstart/adapter-maplibre.md#using-with-mapbox-gl-js) below. > **Configure visually first?** [Open the playground](https://elementeditor.dev/playground) to tweak every setting and copy the resulting config. Pass the same `config` object to ``. --- ## Step 1 — Install ```bash npm install @element-editor/adapter-maplibre @element-editor/ui maplibre-gl ``` If `maplibre-gl` is already in your project, you don't need to reinstall it. Peer dependencies: `react` and `react-dom` `^19.2`, `maplibre-gl` 5.5 or 6. React 18 is not supported. `@element-editor/ui` provides the toolbars and panels. The adapter already depends on it, but list it in your own `package.json` so you can import from it (pnpm and other strict package managers only resolve packages you declare). The same applies to `@element-editor/core` if you want its types and helpers, such as `FeatureCollection` or `getFeatureCollectionBBox`. Keep all `@element-editor/*` packages on the same version. --- ## Step 2 — Import the CSS Add these imports once, near your app entry point: ```tsx import 'maplibre-gl/dist/maplibre-gl.css' import '@element-editor/adapter-maplibre/style.css' ``` The Element stylesheet doesn't include MapLibre's CSS, so import both. The JavaScript entry doesn't import any CSS. The stylesheet doesn't reset your page. Tailwind's base styles apply only inside an element with a `data-elm-theme` attribute, so all editor UI must be rendered inside one (Step 3 shows how). The stylesheet is plain CSS, so the import works in any CSS setup: Vite, webpack, Next.js, with or without Tailwind (including Tailwind v3), or a CSS `@import`. It has no `@layer`, `@tailwind` or `@apply` directives for your build to reinterpret, and every Element rule (utilities included) only matches inside the `data-elm-theme` element and Element's portals, so it can't override your own classes elsewhere on the page, even ones with the same names (`hidden`, `absolute`, `md:flex`, …). Editor UI you render in a container of your own outside that element (a sidebar, your own portal) gets no Element styles: give that container a `data-elm-theme` attribute too (or `data-elm-portal` for a portal). On MapLibre GL JS 6 your map also needs MapLibre's worker URL, set once before the first map (MapLibre 5 has the worker built in). With Vite: ```ts import { setWorkerUrl } from 'maplibre-gl' import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url' setWorkerUrl(workerUrl) ``` For other bundlers see MapLibre's [installation notes](https://maplibre.org/maplibre-gl-js/docs/) and [MapLibre GL JS 6 worker](https://elementeditor.dev/docs/guides/third-party-services.md#maplibre-gl-js-6-worker-maplibreworker). --- ## Step 3 — Build the component MapLibre GL maps are initialised imperatively via `new maplibregl.Map(...)`. Create the map in a `useEffect`, then render `ElementEditorControls` with the map instance, inside `ElementEditorUIProvider`, `GeoStoreProvider` and a `data-elm-theme` element: ```tsx import { useEffect, useRef, useState } from 'react' import * as maplibregl from 'maplibre-gl' import 'maplibre-gl/dist/maplibre-gl.css' import { ElementEditorUIProvider, GeoStoreProvider, ElementEditorControls } from '@element-editor/adapter-maplibre' import '@element-editor/adapter-maplibre/style.css' export default function MyMap() { const containerRef = useRef(null) const mapRef = useRef(null) const [mapReady, setMapReady] = useState(false) useEffect(() => { if (!containerRef.current || mapRef.current) return const map = new maplibregl.Map({ container: containerRef.current, style: 'https://demotiles.maplibre.org/style.json', center: [2.35, 48.86], zoom: 5, }) mapRef.current = map if (map.isStyleLoaded()) { setMapReady(true) } else { map.on('load', () => setMapReady(true)) } return () => { map.remove(); mapRef.current = null } }, []) return (
{/* Map canvas */}
{mapReady && mapRef.current && ( console.log(data)} /> )}
) } ``` > **Note:** `ElementEditorControls` waits until the map's style can accept sources before it adds its layers, so it's safe to render it as soon as the map exists. The `mapReady` state is still needed: changing `mapRef.current` doesn't re-render the component, so the state change is what makes `ElementEditorControls` appear. > **Note:** Placement rules: > - `ElementEditorUIProvider` provides the contexts the editor needs: an error boundary, config, keyboard shortcuts, and events and toasts. `ElementEditorControls` throws without it. It also renders Element's own toast ``, so you don't need to add one. > - `GeoStoreProvider` must wrap `ElementEditorControls`. It creates the store. Use one per editor. > - The `data-elm-theme` element (`"light"` or `"dark"`) scopes the editor's styles and its keyboard shortcuts: a key press only acts on this editor when focus or your last click is inside it. It must contain the map container. --- ## What you get Your existing MapLibre GL map now has Element editing attached: - Drawing tools for areas, lines, points, rectangles, circles, freehand paths, and routes — plus a picker (`X`) that imports shapes from OpenStreetMap - Drag-to-draw rectangles and circles; spacebar pans during drawing without leaving the tool; `⌘ J` keeps the tool active after a shape commits - Click-to-select, multi-select, box-select; right-click context menu on features - Vertex editing, transform (scale/rotate), boolean operations, simplify/smooth/buffer - Group / ungroup with `⌘ G` / `⌘ ⇧ G`; groups carry through to `metadata.groups` - 25-step undo/redo - `onChange` fires after every committed change with the full `FeatureCollection` `ElementEditorControls` adds GL sources and layers to your map for rendering features and interactions. It renders no visible HTML DOM elements by default. To add toolbars and panels, see [Adding the full UI](https://elementeditor.dev/docs/quickstart/adapter-maplibre.md#adding-the-full-ui) below. --- ## Step 4 — Wire up data Pass `initialData` to pre-populate the editor. `onChange` delivers the full `FeatureCollection` after each committed change. The types come from `@element-editor/core` (see Step 1): ```tsx import { useEffect, useRef, useState, useCallback } from 'react' import * as maplibregl from 'maplibre-gl' import 'maplibre-gl/dist/maplibre-gl.css' import { ElementEditorUIProvider, GeoStoreProvider, ElementEditorControls } from '@element-editor/adapter-maplibre' import type { FeatureCollection } from '@element-editor/core' import '@element-editor/adapter-maplibre/style.css' export default function MyMap() { const containerRef = useRef(null) const mapRef = useRef(null) const [mapReady, setMapReady] = useState(false) const savedData: FeatureCollection | null = JSON.parse(localStorage.getItem('my-map') ?? 'null') const handleChange = useCallback((data: FeatureCollection) => { localStorage.setItem('my-map', JSON.stringify(data)) }, []) useEffect(() => { if (!containerRef.current || mapRef.current) return const map = new maplibregl.Map({ container: containerRef.current, style: 'https://demotiles.maplibre.org/style.json', center: [2.35, 48.86], zoom: 5, }) mapRef.current = map if (map.isStyleLoaded()) { setMapReady(true) } else { map.on('load', () => setMapReady(true)) } return () => { map.remove(); mapRef.current = null } }, []) return (
{mapReady && mapRef.current && ( )}
) } ``` If `initialData` isn't a valid `FeatureCollection`, the editor reports an `error` event and starts empty instead of crashing. A single `Feature` is wrapped in a collection. --- ## Adding the full UI `ElementEditorControls` handles the editing layer. Toolbars and panels come from `@element-editor/ui` and are passed as `children` of `ElementEditorControls`. They render inside the adapter's own `MapControllerProvider`, which gives them `flyTo`, `fitBounds` and the other map-controller actions. `FloatingToolbar`, `LayersPanel` and `DataTablePanel` position themselves over the map, against the `data-elm-theme` element (give it `position: relative`). `EditingToolbar`, `ActiveDrawingToolbar` and single buttons such as `FitBoundsButton` render in place, so put them in an absolutely positioned wrapper of your own, as below. `DataTablePanel` writes its open height to `--elm-table-offset` on the `data-elm-theme` element; add it to a bottom-anchored wrapper's `bottom` and the wrapper rides above the open table. The data table and the modals are lazy-loaded, so they must be wrapped in ``. Give each its own boundary: a shared one unmounts the already-loaded siblings while a new one loads. ```tsx import { Suspense, useEffect, useRef, useState } from 'react' import * as maplibregl from 'maplibre-gl' import 'maplibre-gl/dist/maplibre-gl.css' import { ElementEditorUIProvider, GeoStoreProvider, ElementEditorControls } from '@element-editor/adapter-maplibre' import { ThemeContext, FloatingToolbar, EditingToolbar, ActiveDrawingToolbar, FitBoundsButton, LayersPanel, DataTablePanel, ShortcutsModal, SettingsModal, SchemaModal, GeoJSONModal, useUIStore, } from '@element-editor/ui' import '@element-editor/adapter-maplibre/style.css' // Schema and GeoJSON modals render whenever mounted, so mount them only while open. function ConditionalModals() { const schemaOpen = useUIStore((s) => s.schemaModalOpen) const toggleSchema = useUIStore((s) => s.toggleSchemaModal) const codeOpen = useUIStore((s) => s.codeModalOpen) const toggleCode = useUIStore((s) => s.toggleCodeModal) return ( <> {schemaOpen && } {codeOpen && } ) } export default function MyMap() { const containerRef = useRef(null) const mapRef = useRef(null) const [mapReady, setMapReady] = useState(false) useEffect(() => { if (!containerRef.current || mapRef.current) return const map = new maplibregl.Map({ container: containerRef.current, style: 'https://demotiles.maplibre.org/style.json', center: [2.35, 48.86], zoom: 5, }) mapRef.current = map if (map.isStyleLoaded()) { setMapReady(true) } else { map.on('load', () => setMapReady(true)) } return () => { map.remove(); mapRef.current = null } }, []) return (
{/* Map canvas */}
{/* ElementEditor + UI — children of ElementEditorControls get the map controller */} {mapReady && mapRef.current && ( console.log(data)} > {/* Drawing tool selector: positions itself, top center */} {/* Edit actions and finish / cancel drawing: you place these (bottom center here) */}
{/* Fly to fit all features: you place it (bottom left here) */}
{/* Feature list sidebar: positions itself, right */} {/* Spreadsheet view */}
)}
) } ``` `ThemeContext` tells portaled UI (tooltips, menus, modals) which theme to use. Keep its value in sync with `data-elm-theme`. Any UI you portal elsewhere yourself should carry a `data-elm-portal` attribute on its root, so Element styles it and keyboard shortcuts keep working while it has focus. For a complete working example with buttons that open each panel, see [Custom UI with adapters](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md). --- ## Using with MapTiler SDK MapTiler SDK extends `maplibregl.Map` directly. Pass your MapTiler map instance to `ElementEditorControls` as-is — no cast is needed. Keep `maplibre-gl` installed next to it (Step 1): the adapter imports it at runtime for its map markers, and as an optional peer dependency it isn't installed for you. ```bash npm install @maptiler/sdk ``` ```tsx import { Map } from '@maptiler/sdk' import '@maptiler/sdk/dist/maptiler-sdk.css' import { ElementEditorControls } from '@element-editor/adapter-maplibre' // Render inside ElementEditorUIProvider, GeoStoreProvider and a data-elm-theme element, as in Step 3. // Initialise MapTiler map in a useEffect (same pattern as MapLibre): const map = new Map({ container: containerRef.current, style: `https://api.maptiler.com/maps/streets/style.json?key=YOUR_KEY`, center: [2.35, 48.86], zoom: 5, }) // MapTiler SDK extends maplibregl.Map directly — pass it as-is, no cast needed. {mapReady && mapRef.current && ( )} ``` --- ## Using with Mapbox GL JS Mapbox GL JS shares the same API surface as MapLibre GL at runtime. TypeScript requires a cast because the type names differ between packages. `maplibre-gl` must stay installed as well (Step 1): the adapter imports it at runtime for its map markers (vertex and transform handles, measure labels). ```bash npm install mapbox-gl ``` ```tsx import mapboxgl from 'mapbox-gl' import 'mapbox-gl/dist/mapbox-gl.css' import type { Map as MapLibreMap } from 'maplibre-gl' import { ElementEditorControls } from '@element-editor/adapter-maplibre' // Render inside ElementEditorUIProvider, GeoStoreProvider and a data-elm-theme element, as in Step 3. mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN' // Initialise your Mapbox map in a useEffect (same pattern as MapLibre). // Then, when mapReady: {mapReady && mapRef.current && ( )} ``` The cast changes nothing at runtime. The TypeScript declarations of `mapbox-gl` and `maplibre-gl` are incompatible at the type level, but both implement the map methods Element calls. --- ## Optional: built-in basemaps Instead of your own style, you can use Element's basemaps (Streets, Terrain, Light, Dark, OpenStreetMap, and an `'auto'` mode that follows the editor theme) with the `BasemapControl` picker. See the [Basemaps guide](https://elementeditor.dev/docs/guides/basemaps.md#with-the-maplibre-adapter). --- ## What's next - [Adapter reference](https://elementeditor.dev/docs/reference/adapter-maplibre.md) — every prop, event, ref method, and the `useMapLibre()` hook - [Custom UI with adapters](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md) — full `@element-editor/ui` integration pattern with proper modal state management - [Persisting data](https://elementeditor.dev/docs/guides/persisting-data.md) — localStorage, REST APIs, granular events, and the ref API --- # Migrating to 0.2 *Upgrade an app from Element Editor 0.1 to 0.2.* > **New to Element?** You don't need this page. 0.2.0 is the first release on npm; this guide is only for apps built against a 0.1 pre-release build (from the repository, before the npm release). Start with the [quick start](https://elementeditor.dev/docs/quickstart/react.md). The biggest change: `@element-editor/react` now renders a **MapLibre GL** map. The Leaflet editor you used in 0.1 is still there, at `@element-editor/react/leaflet`. Decide which engine you want, then work through the sections that apply. The full list of changes is in the [changelog](https://github.com/spatibase/element/blob/main/CHANGELOG.md). Quick checklist: - [ ] Pick an engine and install its peers ([Install](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#1-install)) - [ ] Fix the import and stylesheet paths ([Imports and CSS](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#2-imports-and-css)) - [ ] Move engine-specific props to the right entry ([Props per entry](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#3-props-that-exist-on-only-one-entry)) - [ ] `bounds` → bbox, `flyTo` → object form ([Coordinates](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#4-bounds-and-flyto-use-lng-lat)) - [ ] Tell users about the `T` / `A` shortcut swap ([Shortcuts](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#5-keyboard-shortcuts)) - [ ] Several editors on one origin? Add `persistKey` ([persistKey](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#6-several-editors-on-one-origin-persistkey)) - [ ] Production traffic? Your own servers and keys in `config.network`; `routingApiKey` → `config.network.routing.apiKey` ([Third-party services](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#7-third-party-services-confignetwork)) - [ ] Adapter users: `data-elm-theme` wrapper and the other adapter changes ([Adapters](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#8-adapter-users)) - [ ] `config.ui.corners` / `config.toolbar.position` → `config.ui.layout` ([Layout](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#9-layout)) - [ ] Next.js App Router ([Next.js](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#10-nextjs-app-router)) - [ ] The rest: licence key, CSS tokens, `onEvent` ([Smaller breaking changes](https://elementeditor.dev/docs/guides/migrating-to-0.2.md#11-smaller-breaking-changes)) --- ## 1. Install React and React DOM **`^19.2`** are required for both engines (React 18 is no longer supported). Every other peer of `@element-editor/react` is optional, so you install only the ones for the entry you import. **MapLibre (the default entry):** ```bash npm install @element-editor/react maplibre-gl ``` `maplibre-gl` must be **5.5 or 6** (the built-in Terrain basemap needs 5.5+). `@element-editor/core`, `@element-editor/ui` and `@element-editor/adapter-maplibre` come in as regular dependencies. **Leaflet (`/leaflet`):** ```bash npm install @element-editor/react @element-editor/adapter-leaflet leaflet react-leaflet ``` `leaflet` `^1.9`, `react-leaflet` `^5` (react-leaflet 4 is no longer supported). These peers are optional, so your package manager won't install them for you. You don't need `maplibre-gl`: the Leaflet entry never loads it. **Adapter packages:** `@element-editor/adapter-maplibre` needs `maplibre-gl` 5.5 or 6 (was `>=4`); `@element-editor/adapter-leaflet` needs `leaflet` `^1.9` and `react-leaflet` `^5`. ## 2. Imports and CSS **Stay on Leaflet** (smallest upgrade: the component API is the same): ```tsx // 0.1 import { ElementEditor } from '@element-editor/react' import '@element-editor/react/style.css' // 0.2 import { ElementEditor } from '@element-editor/react/leaflet' import '@element-editor/react/leaflet/style.css' ``` **Switch to MapLibre:** keep the 0.1 import paths; they now load the MapLibre editor. `@element-editor/react/style.css` bundles `maplibre-gl.css` instead of Leaflet's CSS. ```tsx import { ElementEditor } from '@element-editor/react' import '@element-editor/react/style.css' ``` Import the stylesheet that matches the entry. Mixing them (MapLibre component with the Leaflet stylesheet, or the other way round) gives a broken map with no error. Types and helpers (`ElementEditorRef`, `ElementEditorProps`, `FeatureCollection`, `GeoJSONFeature`, `Schema`, `DEFAULT_LAYOUT`, `IconButton`, `FeatureStyle`, `BBox`, …) are exported from both entries. ## 3. Props that exist on only one entry Everything else (data, schema, tools, theme, layout, events, ref) is shared. | Prop | Default entry (MapLibre) | `/leaflet` | |---|---|---| | `basemaps` | Picker choices (`BasemapInput[]`, vector or raster); `false` hides the picker | Raster only: `(RasterBasemap \| 'osm')[]`. One entry replaces OpenStreetMap, two or more add a picker | | `defaultBasemap` / `basemap` / `onBasemapChange` | Starting basemap (`'auto'`, `'streets'`, `'terrain'`, `'light'`, `'dark'`, `'osm'` or a custom style / raster source) / the basemap controlled by your app / pick callback | Same, with raster entries or `'osm'` | | `tileLayer` | — (ignored, with a dev warning) | Any react-leaflet tile layer; disables the picker | | `renderer` | — (ignored, with a dev warning) | `'canvas'` (default) or `'svg'` | If you pass `tileLayer` to the default entry, the browser console says so in development: either switch the import to `/leaflet` or replace the tile layer with a basemap: ```tsx // 0.1 (Leaflet) } /> // 0.2, MapLibre: a raster basemap ``` Give every custom basemap an `id`: the picker tells entries apart by it, and only entries with an `id` (plus the built-ins and `'auto'`) are remembered. `defaultBasemap` is a starting value (the user's remembered pick wins on reload); `basemap` is controlled: pair it with `onBasemapChange`, and nothing is remembered. See [Basemaps](https://elementeditor.dev/docs/guides/basemaps.md#controlling-the-basemap-from-your-app). ## 4. `bounds` and `flyTo` use `[lng, lat]` The public API now uses GeoJSON order everywhere. The old forms still work in 0.2 and print a one-time development warning (with the converted value). **`bounds`** (both drop-ins and `@element-editor/adapter-leaflet`'s `ElementEditorControls`) takes a bbox `[west, south, east, north]`: ```tsx // 0.1: [[south, west], [north, east]] // 0.2: [west, south, east, north] ``` `bounds` restricts panning. Set the start view with the new `initialView` prop; with nothing else to go on (no `initialView`, remembered view or `initialData`) the map now opens fitted to `bounds`. In 0.2 it is applied on mount too, not only when it changes. `@element-editor/adapter-maplibre` keeps its `maxBounds` prop, which now also accepts a bbox. Code that reads `uiStore.bounds` directly now always gets a bbox. **Start view.** The MapLibre drop-in used to fit the map to `initialData` on every load, over the view the user left it at. It now fits `initialData` only on a first visit (no remembered view); pass `initialView="data"` to keep fitting on every load. `@element-editor/adapter-maplibre`'s `ElementEditorControls` no longer fits the map on mount; call `ref.fitBounds(getFeatureCollectionBBox(fc))` yourself. **`ref.flyTo`** takes an object: ```tsx const ref = useRef(null) // 0.1 ref.current?.flyTo([48.86, 2.35], 12) // [lat, lng] // 0.2 ref.current?.flyTo({ center: [2.35, 48.86], zoom: 12 }) // [lng, lat]; zoom defaults to 15 ``` `ref.fitBounds` already took `[lng, lat]` and is unchanged. Types: `BBox`, `BoundsInput`, `FlyToOptions` from either react entry or `@element-editor/core`. ## 5. Keyboard shortcuts | Action | 0.1 | 0.2 | |---|---|---| | Toggle data table | `V` | `T` | | Toggle transform tool | `T` | `A` | If your docs, onboarding or support material mention these keys, update them. Bindings a user customised in the shortcuts dialog are kept. ## 6. Several editors on one origin: `persistKey` Element remembers UI choices in `localStorage` (theme, settings toggles, units, custom shortcuts, window positions and sizes, panel widths, map view, basemap pick, last schema). By default every editor on the origin shares the same `elm_*` keys, so two editors, on one page or on two pages of one app, overwrite each other's choices. Give each its own key: ```tsx // elm_theme → elm_parcels_theme, … // reads and writes nothing ``` Adapter setups pass the same config to the provider: ``. `BasemapControl`'s `storageKey` is namespaced the same way. Set it once at mount. Adding a `persistKey` to an editor that already has users moves its keys, so returning visitors start from your defaults once (their old `elm_*` values aren't migrated). Details: [Persisting data](https://elementeditor.dev/docs/guides/persisting-data.md#elements-own-saved-state-persistkey--persist). ## 7. Third-party services: `config.network` Element calls public services by default: basemap tiles and fonts (OpenFreeMap, Mapterhorn, OpenStreetMap), the Picker's Overpass lookups, the Route tool's router (the **OSRM demo server: car-only, not for production**) and the search box's geocoder (Nominatim). For production, point them at your own servers or paid plans in one place, per editor: ```tsx fetch(url, { ...init, headers: { ...init?.headers, Authorization: 'Bearer …' } }), }, }} /> ``` - **`routingApiKey`** still works (deprecated, dev warning); `config.network.routing.apiKey` wins when both are set. - `false` turns a service off and hides what needs it: `routing: false` (Route tool), `nominatim: false` (search box), `overpass: false` (the Picker reads only the vector tiles; hidden on Leaflet). - Swapped servers need their own credits: give `attribution`. The Nominatim credit now shows only while the search box is offered; ORS gets its credit. - If you built against a 0.2 pre-release: `configureOverpass()` (page-wide) is gone, use `config.network.overpass` + `fetch`; the `spriteUrl` prop and the `spriteUrl` option of `BasemapControl` / `useBasemap` / `loadBasemapStyle` / `setBasemap` are gone, use `config.network.sprite` (`{ network }` option). Every service, its licence and how to self-host it: [Third-party services and self-hosting](https://elementeditor.dev/docs/guides/third-party-services.md). A failed Picker lookup still rejects with an `OverpassError` whose `code` is `'rate-limited' | 'busy' | 'timeout' | 'network'`. ## 8. Adapter users These apply if you use `@element-editor/adapter-leaflet` or `@element-editor/adapter-maplibre` with your own map. **Wrap the editor in `data-elm-theme`.** The stylesheets no longer apply Tailwind's preflight to your whole page; base styles apply only inside `[data-elm-theme]`. Render the map and all editor UI inside such an element, or the UI renders unstyled: ```tsx
{/* your map + + any @element-editor/ui panels */}
``` Use `"light"` or `"dark"`. The same element scopes keyboard shortcuts: a key acts on this editor only when focus or the last click is inside it. Portaled UI of your own should carry a `data-elm-portal` attribute. The drop-ins do all of this for you. **Toasts.** `ElementEditorUIProvider` renders its own `` now; remove the one you added for Element (or pass `toaster={false}` to keep yours). With `onEvent` set, the editor shows no toasts at all; every message goes to your handler. **Errors (`onError`).** `ElementEditorUIProvider`'s `onError` used to fire only for render crashes; it now fires for every runtime failure (rate limits, a failed basemap, an invalid import, `maxFeatures`, …) with an `ElementEditorError`. It is still an `Error`, so `(error: Error) => void` handlers keep compiling; if yours means "the editor crashed", check `error.code === 'crash'`. The `onEvent` `error` event now carries `code` and `source`. Hint-like messages (a vertex that can't be deleted, an invalid zoom value, nothing to export) are `warning` events now, not `error`. See [Events → onError](https://elementeditor.dev/docs/reference/events.md#onerror). If you build on `@element-editor/core` directly: ```ts // 0.1: a string createDataStore({ onError: (message) => toast(message) }) uiStore.getState().reportError('Something failed') // 0.2: an ElementEditorError, plus { quiet } for failures that should not be toasted createDataStore({ onError: (error, opts) => { if (!opts?.quiet) toast(error.message) } }) uiStore.getState().reportError(new ElementEditorError('network', 'basemap', 'Something failed')) ``` `dataStore.copySelection()` now returns a `Promise` (true when the system clipboard was written too). **`maxFeatures` in the store.** `maxFeatures` / `setMaxFeatures` moved from the UI store to the data store: ```ts // 0.1 const max = useUIStore((s) => s.maxFeatures) // 0.2 const max = useDataStore((s) => s.maxFeatures) ``` Adding actions (`duplicateFeature`, paste, …) return `false` when the limit refuses them, `addFeature` returns `null` (otherwise the stored feature); `canAddFeatures(n)` checks ahead. If you built against a 0.2 pre-release: **`BasemapControl`** (MapLibre adapter) no longer restyles your map on mount unless you pass `value` or `defaultValue`, or a pick was remembered under `storageKey`. Pass `defaultValue="auto"` to keep the old behaviour. ## 9. Layout **`config.ui.corners` and `config.toolbar.position` are removed.** Place every control with `config.ui.layout` ([Configuring layout](https://elementeditor.dev/docs/guides/configuring-layout.md)). `toolbar.direction` stays. | 0.1 | 0.2 | |---|---| | `toolbar: { position: 'top-left' }` (… `'bottom-right'`, `'left-center'`, …) | `ui: { layout: withLayout({ move: { toolbar: 'topLeft' } }) }` | | `ui.corners.: { items, direction }` | `ui.layout.: { items, direction }` (list `toolbar` and `leftCenter: [{ group: ['undo', 'redo'] }]` too: unlisted controls are hidden) | | `'toolbar'` in a corner's `items` | the same, `'toolbar'` in that slot | ```ts import { withLayout } from '@element-editor/react' // 0.1 config={{ toolbar: { position: 'bottom-right' } }} // 0.2 config={{ ui: { layout: withLayout({ move: { toolbar: 'bottomRight' } }) } }} // 0.1 (once any corner was given, the other corners were empty) config={{ ui: { corners: { topRight: { items: ['table', 'settings'] } } } }} // 0.2 config={{ ui: { layout: { topCenter: ['toolbar'], leftCenter: [{ group: ['undo', 'redo'] }], topRight: ['table', 'settings'] } } }} ``` The rest of this section only matters if you built against a 0.2 pre-release (`DEFAULT_LAYOUT` and the layout types are new in 0.2). **`DEFAULT_LAYOUT` is frozen** (every editor on the page shares it). Don't mutate or re-list it; change it with `withLayout`: ```ts // before const layout = { ...DEFAULT_LAYOUT, statusRight: ['attribution'] } // 0.2 (the spread still works when the slots you add don't repeat a default control) const layout = withLayout({ move: { attribution: 'statusRight' } }) ``` **Layout types are slot-specific.** A control in a slot it can't go to (`'attribution'` or a bare `'separator'` on the map, `'toolbar'` / `'applyChanges'` in the status bar, `{ items, direction }` on a status slot) is now a compile error instead of a runtime warning. Build a layout in a variable with `satisfies LayoutConfig` (or a `LayoutConfig` annotation) so the strings stay literal. **Layout helpers.** `resolveLayout`, `LAYOUT_SLOTS`, `isControlVisible` and `visibleLayoutEntries` are no longer public. Use `resolveConfig(config).ui.layout` for the resolved layout, and `DEFAULT_LAYOUT` / `withLayout` to build one. ## 10. Next.js App Router Both `@element-editor/react` entries, `@element-editor/ui` and both adapters now start with `'use client'`, so importing them from a Server Component no longer throws. That only marks the client boundary: Next.js still server-renders client components, and Leaflet touches `window` as soon as it is imported. Keep loading the editor with `dynamic(..., { ssr: false })` from a client wrapper, for either entry: ```tsx // app/components/MapEditor.tsx 'use client' import dynamic from 'next/dynamic' const ElementEditor = dynamic( () => import('@element-editor/react/leaflet').then((m) => m.ElementEditor), // or '@element-editor/react' { ssr: false }, ) export default function MapEditor() { return (
) } ``` Import the matching stylesheet in your root layout. No `transpilePackages` or worker configuration is needed. More in [Using Element with Next.js](https://elementeditor.dev/docs/guides/nextjs.md). ## 11. Smaller breaking changes - The `licenseKey` prop is gone: the community edition is MIT. - `theme` sets only the mode: `'light' | 'dark' | 'auto'`. Its object form (CSS variables for the root) is gone; pass them through `style` instead, `theme={{ '--elm-accent': '#7c3aed' }}` → `style={{ '--elm-accent': '#7c3aed' }}` (or `accentColor="#7c3aed"`). An object passed to `theme` is ignored with a development warning. - The unused 0.1 CSS tokens (surface/border/text/shadow) were removed. 0.2 has working design tokens instead (`--elm-surface`, `--elm-text`, `--elm-border`, `--elm-radius`, `--elm-font`, `--elm-shadow`, …): see [Theming](https://elementeditor.dev/docs/guides/theming.md#approach-2--design-tokens). - Polygons with self-intersecting edges are no longer flagged. - `@element-editor/core` no longer exports the unused import/export/validation workers; `@element-editor/adapter-maplibre` no longer exports `DrawingCursorHint`. - The packages export a smaller, documented API. Helpers the packages share among themselves (Mercator and topology math, click guards, the shortcut-binding cache, picker tile helpers, schema defaults, …) left the `@element-editor/core` root; the adapters dropped duplicate and plumbing exports (`FitBoundsInteraction`, the Leaflet `FeatureLayer`, the MapLibre `init*Layers` / `cleanup*Layers` functions, …). The full list is in the [changelog](https://github.com/spatibase/element/blob/main/CHANGELOG.md) under 0.2.0, "Removed from the public API". - `onEvent` now receives every user-facing message, and with it set the editor shows no toasts at all. - If you built against a 0.2 pre-release: `@element-editor/ui` dropped `danger` from `ContextMenu` items, `EditToolbarBtn` and `Button` (delete actions are no longer red), and the `ToolBar` export and `@element-editor/ui/style.css` (import the stylesheet of the entry or adapter you use). - `setRoutingApiKey()` and the `routingApiKey` prop are deprecated; use `config.network.routing.apiKey`. --- # Persisting data *Get feature data out of the editor and into your storage layer.* Element Editor manages features in memory. To keep them across page reloads or share them with other users, you need to persist them. This guide covers four patterns — from a two-liner for prototypes to granular event hooks for real-time sync. --- ## Pattern 1 — localStorage The fastest path for prototypes and local-only tools. The editor rehydrates from storage on every page load. ```tsx import { ElementEditor } from '@element-editor/react' import type { FeatureCollection } from '@element-editor/react' export default function App() { const saved = localStorage.getItem('my-map') return ( localStorage.setItem('my-map', JSON.stringify(data))} /> ) } ``` > **Note:** `onChange` fires on every committed change, including each vertex drag (once, when it ends). For large feature sets, consider debouncing or switching to granular events (see Pattern 3 below). It doesn't fire for the `initialData` load itself, so restoring data never writes it straight back. Element doesn't care if you never call `onChange`. It will happily draw polygons into the void, perfectly content. --- ## Pattern 2 — POST to an API For production apps, send the full `FeatureCollection` to your backend on every committed change. ```tsx import { useCallback } from 'react' import { ElementEditor } from '@element-editor/react' import type { FeatureCollection } from '@element-editor/react' export default function App() { const handleChange = useCallback(async (data: FeatureCollection) => { await fetch('/api/map', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }) }, []) return } ``` The `FeatureCollection` passed to `onChange` includes the `metadata` envelope containing schema definitions and groups — round-trip it faithfully and pass it back via `initialData` to restore the full editor state. To load initial data from your API, pass it as `initialData` when it arrives: ```tsx const [initialData, setInitialData] = useState(null) useEffect(() => { fetch('/api/map') .then((r) => r.json()) .then(setInitialData) }, []) // Mounts empty; the data is applied once when it arrives (no undo step, no onChange, and the // map fits it on a first visit). The editor stays usable while loading. return ``` Data that arrives late is applied only while the editor is still empty and the user hasn't edited (otherwise it is ignored, so their edits are kept), and only once: a later change of `initialData` is ignored, with a development warning. To swap the data afterwards, see [Loading data back after mount](https://elementeditor.dev/docs/guides/persisting-data.md#loading-data-back-after-mount). If you'd rather not show an empty editor while loading, render it only when the data is there (`initialData ? :

Loading…

`). `initialData` takes any GeoJSON: a `GeoJSON.FeatureCollection` from `@types/geojson` type-checks as is, and plain files without Element's `metadata` load with the default schema. --- ## Pattern 3 — Granular events `onChange` reconstructs the full `FeatureCollection` on every committed change. For 500+ features, this means sending potentially thousands of features on every vertex move. Granular events deliver only the affected feature. ```tsx import { ElementEditorControls } from '@element-editor/adapter-leaflet' // or adapter-maplibre { db.features.insert(feature) }} onFeatureUpdate={(id, feature) => { db.features.update(id, feature) }} onFeatureDelete={(id) => { db.features.delete(id) }} /> ``` Granular events and `onChange` can coexist. You can use `onChange` for a periodic full-save and `onFeatureAdd/Update/Delete` for real-time incremental sync simultaneously. `onSelectionChange` fires independently of data changes — use it to react to the user's current selection without triggering a save: ```tsx setHighlightedIds(ids)} /> ``` --- ## Pattern 4 — Save on demand (ref API) For cases where you want an explicit Save button rather than auto-save on every change. ```tsx import { useRef } from 'react' import { ElementEditor } from '@element-editor/react' import type { ElementEditorRef } from '@element-editor/react' import type { FeatureCollection } from '@element-editor/react' export default function App() { const ref = useRef(null) function handleSave() { const data = ref.current?.getFeatureCollection() if (data) localStorage.setItem('my-map', JSON.stringify(data)) // or send it to your API } return ( <>
) } ``` `getFeatureCollection()` returns a snapshot of the current state. It does not trigger `onChange`. For the adapter packages (`@element-editor/adapter-leaflet`, `@element-editor/adapter-maplibre`), the ref type is `ElementEditorControlsRef`. It has the same methods as `ElementEditorRef`. --- ## Loading data back after mount `initialData` is the starting data (see above). To swap data imperatively after mount — for example, after the user opens a different project — call the ref: ```tsx // @element-editor/react ref.current?.importGeoJSON(newData) // replace (default) ref.current?.importGeoJSON(extra, 'merge') // append // Like importGeoJSON(newData, 'replace'), on all three packages: ref.current?.setFeatureCollection(newData) ``` > **Note:** these loads fire `onChange` (and `onFeatureAdd` / `onFeatureDelete`) like any other change, and are one undo step. If you save in `onChange`, loading from your backend would save the same data straight back. Pass `{ silent: true }` to skip the data callbacks for that load, and `{ undoable: false }` if the user shouldn't be able to undo back to the previous project (it also clears the undo history): > > ```tsx > const data = await (await fetch(`/api/projects/${id}`)).json() > ref.current?.setFeatureCollection(data, { silent: true, undoable: false }) > ``` Replacing with features whose ids are already in the editor keeps them (re-importing the same data is safe). In `'replace'` mode only ids repeated within the incoming data count as `duplicates`; in `'merge'` mode, ids already in the editor are skipped too. This preserves zoom, selection, and undo history. If you want a clean slate (reset zoom, collapse panels, clear undo), remount with a new `key` prop instead: ```tsx ``` --- ## TypeScript imports ```ts // @element-editor/react re-exports the data types: import type { FeatureCollection, GeoJSONFeature, Schema } from '@element-editor/react' // The adapters don't. With an adapter, import them from @element-editor/core // (add it to your package.json, same version as the adapter): import type { FeatureCollection, GeoJSONFeature, Schema } from '@element-editor/core' ``` --- ## Element's own saved state (`persistKey` / `persist`) Separately from your features, the editor remembers the visitor's UI choices in `localStorage`. By default every editor on an origin shares the same `elm_*` keys, so two editors (two pages of one app, or two editors on one page) overwrite each other's choices. Give each one its own key: ```tsx // elm_theme → elm_parcels_theme, … // reads and writes nothing ``` - **`config.persistKey?: string`** prefixes every key below: `elm_` becomes `elm__`. Default: none (the plain `elm_*` keys, so existing visitors keep their saved state). - **`config.persist?: boolean`** (default `true`). `false` reads nothing and writes nothing: every load starts from your config and props. Both work the same with the drop-ins and with adapters (`ElementEditorUIProvider config={…}`). Set them once at mount; changing them later isn't supported. | Key | What | |---|---| | `elm_theme` | Light / Dark / Auto picked in settings | | `elm_showMeasurements`, `elm_showFeatureNameOnHover`, `elm_topoEditEnabled`, `elm_autoExitAfterDraw` | Settings toggles | | `elm_units` | Units override picked in settings | | `elm_shortcuts` | Custom keyboard shortcuts | | `elm_lastSchemaId` | Schema used for the last new feature | | `elm_panel_prefs`, `elm_panel_width` | Layers panel sections and width | | `elm_code_docked`, `elm_code_dock_width`, `elm_code_win`, `elm_code_win_size` | GeoJSON inspector: docked or floating, dock width, window position and size | | `elm_settings_win(_size)`, `elm_schema_win(_size)`, `elm_feature_win(_size)`, `elm_shortcuts_win(_size)` | Other windows' position and size | | `elm_mapView` | Last map centre and zoom (drop-ins); the start view unless `initialView` is set | | `elm_basemap` / `elm_basemap_leaflet` | Basemap picked in the MapLibre / Leaflet drop-in (not with a controlled `basemap` prop) | `BasemapControl`'s `storageKey` is namespaced the same way. The storage helpers below take the same scope as an optional last argument (`readStorage(key, { persistKey })`), so your own keys can follow it too. --- ## Clean coordinates Element stores coordinates as the map reports them. Drag a shape across a world copy and you get longitudes like `190` or `-540`; every value carries about 15 decimals. [RFC 7946](https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.1) positions are `[longitude, latitude]` in WGS 84, and most back ends expect longitude in range and a sane precision. Cleaning up in `onChange` leaves your data different from the editor's, so the next undo hands you the unrounded copy. Ask Element to do it instead: ```tsx ``` Both parts are off by default, because `wrap` changes what you see on a map that shows repeated worlds (a shape drawn on the right-hand copy jumps to the main one). - `wrap: true` shifts each feature as a whole by a multiple of 360° so the centre of its longitude range (the middle of its bounding box) lies in [-180, 180]. The centre is used so the result does not depend on where a ring starts. Vertices stay continuous, so a shape that crosses the antimeridian keeps its outline, with one side beyond ±180. Element does not split such shapes at ±180. Latitude is left alone unless it is beyond ±90, where it is clamped. - `precision: n` rounds x and y to `n` decimals (integer 0 to 15; 6 is about 0.1 m). Altitude (a third value) is never touched. If rounding makes consecutive vertices identical, they are merged only when the line or ring stays valid; otherwise the rounded values stay as they are. The clean-up runs on every committed change: drawing, vertex edits, moves, boolean operations, import, paste, `initialData`, and ref methods like `addFeature`. Live previews during a drag are not rounded; the value written when you let go is. The store, `onChange`, `exportGeoJSON()` and the undo history hold the same values. Setting the option on an editor that already has data cleans that data once, without an undo step. `precision` here is separate from `config.units.precision`, which only affects displayed numbers. --- ## Persisting your own app state with a version guard If you store app-specific preferences alongside Element's own keys, use the versioned helpers from `@element-editor/core` so a shape change doesn't silently drop (or, worse, silently corrupt) stored values when users upgrade. ```ts // @element-editor/core is installed with every ElementEditor package; add it to your package.json to import it. import { readPersisted, writePersisted } from '@element-editor/core' type MyPrefs = { unit: 'metric' | 'imperial'; sidebar: 'left' | 'right' } const KEY = 'myapp_prefs' const VERSION = 2 const prefs = readPersisted(KEY, VERSION, (raw) => { if (!raw || typeof raw !== 'object') return null const v = raw as Partial if (v.unit !== 'metric' && v.unit !== 'imperial') return null if (v.sidebar !== 'left' && v.sidebar !== 'right') return null return { unit: v.unit, sidebar: v.sidebar } }) ?? { unit: 'metric', sidebar: 'right' } writePersisted(KEY, VERSION, prefs) ``` **Semantics:** - `writePersisted` wraps the value in `{ v: VERSION, data: value }`. - `readPersisted` returns the inner `data` when the envelope matches the current version. If the stored version is older it returns `null` (and logs a dev-mode warning), so callers fall back to defaults instead of loading a stale shape. - Legacy unversioned values written by an older release are accepted **once** on first read — the next `writePersisted` call re-seals them in the envelope. - The optional `parse` argument is your shape guard: return `null` to reject malformed stored data. Bump `VERSION` whenever you change the persisted shape — users will silently fall back to the default and their next save re-seals the new shape. `@element-editor/core` also exports `readStorage(key)` and `writeStorage(key, value)`: raw `localStorage` string access that never throws. In a sandboxed or storage-blocked iframe, `readStorage` returns `null` and `writeStorage` does nothing, instead of throwing a `SecurityError`. Element guards all its own storage access the same way. Element uses the versioned helper internally for `elm_mapView`, `elm_shortcuts`, `elm_panel_prefs`, and the modal window positions. --- ## What's next - [Working with large datasets](https://elementeditor.dev/docs/guides/saving-large-datasets.md) — granular events, viewport culling, geometry workers - [Reference: events](https://elementeditor.dev/docs/reference/events.md) — full event API documentation - [Reference: @element-editor/react](https://elementeditor.dev/docs/reference/element-editor-react.md) — `ElementEditorRef` interface --- # Live mode vs submit mode *When to listen to every edit, when to wait for a Save click.* `` doesn't decide when to persist your data — you do. There are two patterns, picked by which callbacks you wire up. This page walks through both with concrete code, network shapes, and the trade-offs. --- ## The short version | | Live mode | Submit mode | |---|---|---| | **Wired prop** | `onChange` | `onSubmit` (+ optional `onChange`) | | **When data goes to your backend** | When *you* decide (per change, debounced, manual save button…) | When the user clicks **Apply changes** | | **Validation** | You run it yourself | Built-in: gates the submit | | **Network frequency** | Up to you (often: many small PATCHes) | Exactly one POST per submit | | **UX message** | "Edits are auto-saved" | "Drafting until you confirm" | | **Best for** | Internal tools, dashboards, real-time collaboration, Notion-likes | Public forms, listings, admin "save zone" flows, multi-step wizards | --- ## Live mode — `onChange` only You provide an `onChange` callback. Element Editor fires it with the current `FeatureCollection` after every committed edit (drawing, dragging, deleting, property change). What you do with the data is entirely your call. ```tsx import { ElementEditor, type FeatureCollection } from '@element-editor/react' import { useDebouncedCallback } from 'use-debounce' export function ZoneEditor({ zones }: { zones: FeatureCollection | null }) { // e.g. loaded from your API // Save debounced — one network call per second of inactivity const debouncedSave = useDebouncedCallback((data: FeatureCollection) => { fetch('/api/zones', { method: 'PUT', body: JSON.stringify(data) }) }, 1000) // initialData is the starting data (applied once, also if `zones` arrives after mount); the editor owns the data after that return } ``` **Variations on the same pattern:** - Save on every change (no debounce) — chatty but simple - Buffer in component state, flush manually with your own button — custom save UX - Push over WebSocket for real-time collaboration - Write to `localStorage` for offline-first apps (see [Persisting data](https://elementeditor.dev/docs/guides/persisting-data.md)) **No Apply changes button.** The editor is "live" — the canvas *is* the saved state. --- ## Submit mode — `onSubmit` provided You provide an `onSubmit` callback. Element renders an **Apply changes** primary button (last in the bottom-left controls by default; it's the `'applyChanges'` layout entry). The user can edit freely — nothing leaves the editor — until they click the button. ```tsx import { ElementEditor, type Schema } from '@element-editor/react' import { toast } from 'sonner' import { useRouter } from 'next/router' const zoneSchema: Schema = { id: 'zone', name: 'Delivery zone', fields: [ { key: 'name', label: 'Name', type: 'text', required: true }, { key: 'fee', label: 'Delivery fee ($)', type: 'number', required: true }, ], } export function NewZonePage() { const router = useRouter() return ( { await fetch('/api/zones', { method: 'POST', body: JSON.stringify(data) }) router.push('/zones') }} onValidationError={(errors) => { const count = Object.keys(errors).length // `toast` is your app's own sonner instance: render your own for it. // ElementEditor's built-in only shows the editor's own toasts. toast.error(`${count} feature${count > 1 ? 's' : ''} have validation errors`) }} /> ) } ``` **What happens when the user clicks Apply changes:** 1. Element runs schema validation against every feature. 2. If any feature has errors → fires `onValidationError({ [featureId]: ['error msg', …] })` and **does not submit**. 3. If clean → fires `onSubmit(data)` exactly once with the cleaned `FeatureCollection`. The button only renders when `onSubmit` is provided. Removing the prop removes the button — same component, different mode. You can also fire the same flow imperatively: ```tsx const ref = useRef(null) // later ref.current?.submit() ``` `submit()` returns `true` if `onSubmit` fired and `false` if validation blocked it. --- ## Combining both You can wire both. `onChange` fires continuously (e.g. for live previews elsewhere in your UI); `onSubmit` is the explicit "save" moment. ```tsx setLivePreview(data)} // sidebar count, live map elsewhere, etc. onSubmit={(data) => persistToBackend(data)} // the explicit save /> ``` Useful when you want a side panel showing "5 zones drawn (3 unsaved)" or a real-time mini-map elsewhere on the page. --- ## Backend shape implications **Live mode** typically maps to: - `PUT /api/resource` to overwrite a single resource on every (debounced) change - `PATCH` for delta-style sync - WebSocket frames for real-time collaboration - IndexedDB / localStorage for offline-first **Submit mode** typically maps to: - One `POST /api/resource` per click — clean transaction - Form-multipart submission alongside other inputs (zone name, photo upload, etc.) - Wizard step commits Neither pattern is "better" — they describe different products. A weather-monitoring dashboard wants live mode; a delivery-zone admin tool wants submit. --- ## Related props - [`onValidationError`](https://elementeditor.dev/docs/reference/events.md#onvalidationerror) — fires when submit-mode validation blocks - [`onFeatureSelect`](https://elementeditor.dev/docs/reference/events.md#onfeatureselect) — independent of mode; fires whenever the user clicks a feature - [`onEvent`](https://elementeditor.dev/docs/reference/events.md#onevent) — every message the editor would show as a toast (errors, warnings, confirmations, undo); providing it silences the built-in toasts - [`config.ui.layout`](https://elementeditor.dev/docs/guides/configuring-layout.md) — control where the **Apply changes** button (`'applyChanges'`) lives (default: end of `bottomLeft`) --- ## What's next - [Persisting data](https://elementeditor.dev/docs/guides/persisting-data.md) — concrete examples for localStorage, REST APIs, and databases - [Schema and validation](https://elementeditor.dev/docs/guides/schema-and-validation.md) — define the field rules that gate submit-mode - [Reference: events](https://elementeditor.dev/docs/reference/events.md) — every callback, when it fires, and the firing order --- # Schema and validation *Give your features structured, typed properties.* By default, features have an empty `properties` object. Schemas let you define named fields with types and validation rules, so users can fill in structured data alongside their geometry. A restaurant marker can carry a cuisine type, rating, and website. A land parcel can carry an owner name, area class, and last-survey date. This is Element Editor's core differentiator from basic GeoJSON editors. --- ## What a schema is A schema is a named set of typed fields. Each field has a `key` (auto-generated slug), a display `label`, a `type`, and optional constraints like `min`, `max`, and `options`. The `key` is what appears as the property name on each feature. Each feature carries a `schemaId` that links it to a schema definition. When the user selects a feature, the property form renders the fields from that schema. Multiple schemas can coexist in a single editor instance. --- ## Defining a schema via props Pass a `Schema` object to the `schema` prop of `@element-editor/react`. This becomes the default schema — the one applied to new features automatically. ```tsx import { ElementEditor } from '@element-editor/react' import type { Schema } from '@element-editor/react' const locationSchema: Schema = { id: 'location', name: 'Location', fields: [ { key: 'name', label: 'Name', type: 'text', required: true }, { key: 'category', label: 'Category', type: 'select', required: false, options: ['park', 'hospital', 'school'] }, { key: 'capacity', label: 'Capacity', type: 'number', required: false, min: 0 }, { key: 'notes', label: 'Notes', type: 'textarea', required: false }, { key: 'website', label: 'Website', type: 'url', required: false }, { key: 'verified', label: 'Verified', type: 'boolean', required: false }, { key: 'surveyed', label: 'Surveyed', type: 'date', required: false }, ], } export default function App() { return (
console.log(data)} />
) } ``` If a schema with the same `id` already exists in `initialData`, the prop is ignored — the stored schema takes precedence. --- ## Field types | Type | Renders as | Constraints | |---|---|---| | `text` | Single-line text input | — | | `textarea` | Multi-line text input | — | | `number` | Number input | `min`, `max` | | `url` | URL input with link preview | — | | `select` | Dropdown | `options: string[]` | | `date` | Date picker | — | | `boolean` | Checkbox | — | --- ## Multiple schemas The `schema` prop sets the default schema. Users can define additional schemas via the schema editor — open it with the `S` key or the schema button (bottom left by default). All schemas travel with the `FeatureCollection` in the `metadata.schemas` array. Each new feature is assigned the default schema when it is created. The user can change a feature's schema from the property panel. --- ## What a feature looks like in `onChange` data When a user fills in property fields, the values appear in `properties` using the field `key` as the property name. The `schemaId` links the feature back to its schema definition. ```json { "type": "FeatureCollection", "metadata": { "schemas": [ { "id": "location", "name": "Location", "fields": [ { "key": "name", "label": "Name", "type": "text", "required": true }, { "key": "category", "label": "Category", "type": "select", "required": false, "options": ["park", "hospital", "school"] } ] } ], "groups": [] }, "features": [ { "type": "Feature", "id": "f1a2b3c4", "schemaId": "location", "geometry": { "type": "Point", "coordinates": [2.35, 48.85] }, "properties": { "name": "Parc Monceau", "category": "park" } } ] } ``` Pass this `FeatureCollection` back as `initialData` and the editor will restore both the schema definitions and the feature properties. --- ## Non-destructive field removal Removing a field from a schema does not delete existing property data from features. The field definition is removed from `metadata.schemas`, and the property form stops showing it — but the raw value remains in `properties` on every feature that had it filled in. This means you can safely remove a field, later re-add it with the same `key`, and find the old values still present. Data is never silently discarded by a schema change. --- ## Validation and the submit flow The `schema` prop and `onSubmit`/`onValidationError` callbacks are available on `@element-editor/react` and on both adapters' `ElementEditorControls`. When a submit is triggered (on ``, the "Apply changes" button, which appears when `onSubmit` is provided; on any package, `ref.submit()`), Element checks that all `required` fields on all features are filled, and that `number` fields respect their `min`/`max` bounds. ```tsx import { ElementEditor } from '@element-editor/react' import type { FeatureCollection } from '@element-editor/react' { // errors: Record // Keys are feature IDs, values are arrays of error messages console.log('Validation failed:', errors) // Example: { "f1a2b3c4": ["Name is required"] } }} onSubmit={(data: FeatureCollection) => { // Only reached when every required field on every feature passes validation fetch('/api/map', { method: 'POST', body: JSON.stringify(data) }) }} /> ``` `onSubmit` and `onChange` are independent. `onChange` fires on every committed change regardless of validation state. `onSubmit` only fires when validation passes. Use `onChange` for auto-save and `onSubmit` for explicit form submission. Inline validation errors are shown in the property form as the user types — the `onValidationError` callback is for the application layer to handle the failure at submission time. --- ## Passing schemas with adapters The adapters' `ElementEditorControls` accept the same `schema` prop: ``. To ship several schemas, or schemas together with features, put them in `metadata.schemas` of `initialData`. Users can then modify schemas in the schema editor if you include `SchemaModal` from `@element-editor/ui` in your layout. The adapters don't re-export the data types, so import them from `@element-editor/core` (add it to your `package.json`). ```tsx import type { FeatureCollection, Schema } from '@element-editor/core' import { ElementEditorControls } from '@element-editor/adapter-maplibre' const mySchema: Schema = { id: 'poi', name: 'Point of Interest', fields: [ { key: 'name', label: 'Name', type: 'text', required: true }, ], } const initialData: FeatureCollection = { type: 'FeatureCollection', metadata: { schemas: [mySchema], groups: [] }, features: [], } console.log(data)} /> ``` --- ## What's next - [Reference: types](https://elementeditor.dev/docs/reference/types.md) — `Schema`, `SchemaField`, `FieldType` interfaces - [Reference: @element-editor/react](https://elementeditor.dev/docs/reference/element-editor-react.md) — full `ElementEditorProps` table including `schema`, `onSubmit`, `onValidationError` - [Custom UI with adapters](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md) — how to include `SchemaModal` in an adapter layout --- # Configuring the editor layout *Where every button sits, how buttons group and stack, and how to slot your own UI alongside the built-ins.* `` places every built-in control through one option: **`config.ui.layout`**, a map of *slots* to ordered *entries*. The drawing toolbar, undo and redo, the small map buttons, the status bar and the map attribution all go through it. > Configuring this visually first is much faster: [open the playground](https://elementeditor.dev/playground), drag the knobs around, copy the resulting code. --- ## Live preview The same editor in a few common setups. Switch between them and press **Code** to see the props. --- ## Slots Ten slots: eight on the map and two in the status bar under it. ``` ┌──────────────────────────────────────────────┐ │ topLeft topCenter topRight │ │ │ │ leftCenter rightCenter │ │ │ │ bottomLeft bottomCenter bottomRight │ ├──────────────────────────────────────────────┤ │ statusLeft statusRight │ ← status bar └──────────────────────────────────────────────┘ ``` ```tsx ``` - **Order.** Entries render in array order. The **first entry sits at the slot's edge**: in the right slots it's the rightmost, in the bottom slots the lowest (vertical) one. Center slots are centered on their edge. In the status bar, `statusLeft` sits at the left edge and `statusRight` at the right edge, both read left to right. - **Direction.** A slot is an array, or `{ items, direction }` to pick `'horizontal'` or `'vertical'`. Defaults: `leftCenter` and `rightCenter` vertical, every other slot horizontal. The status bar is always horizontal. - **No overlap.** The three slots on the top edge share one row, and so do the three on the bottom edge. They push each other aside instead of overlapping; if they don't fit side by side, the row wraps. On the left and right edges, `leftCenter` / `rightCenter` stay centered while there's room and otherwise move down (or up) to clear the slots above and below them, e.g. a tall vertical `topLeft` column. Right-side slots stay clear of the open layers panel, and bottom slots ride above the data table (and above the bottom panel in `layout="split"`). - **Narrow editors.** Layout follows the editor's own width, not the window's, so an embedded editor behaves the same as a full-page one. When a row is too narrow, a slot wraps its own buttons onto a second line (bottom slots wrap upwards), the drawing toolbar's search box turns into a magnifying-glass button whose box opens under the toolbar, and if the tools still don't fit the toolbar wraps too. Below 640 px the layers panel starts collapsed and, like the docked GeoJSON inspector, opens on top of the map instead of beside it (the buttons don't move aside for it). The editing toolbars at the bottom always stay inside the map and wrap when they have to. - **Editing toolbars.** The toolbars that appear while you edit (selected-feature actions, drawing, Simplify/Smooth/Buffer, the read-only banner) keep their spot at the bottom center. Entries you put in `bottomCenter` sit below them. If they'd overlap `bottomLeft` or `bottomRight`, they move up above the bottom row. ### Default With no `layout`, the editor uses `DEFAULT_LAYOUT`: ```ts { topCenter: ['toolbar'], leftCenter: [{ group: ['undo', 'redo'] }], bottomLeft: ['basemap', 'fitBounds', 'locate', 'zoomIndicator', 'table', 'schema', 'geojson', 'settings', 'keyboard', 'applyChanges'], } ``` Once you set `layout`, you take full control: **a control you don't list is hidden** (except the map attribution, see below). ### Moving one control: `withLayout` To move, add or hide a few controls and keep everything else where it is, use `withLayout(patch, base = DEFAULT_LAYOUT)`. It returns a plain layout object: ```tsx import { withLayout } from '@element-editor/react' // The table button goes top-right; everything else stays put. config={{ ui: { layout: withLayout({ move: { table: 'topRight' } }) } }} // Credits into a status bar, locate first in bottom-right, no keyboard button. config={{ ui: { layout: withLayout({ move: { attribution: 'statusRight', locate: { slot: 'bottomRight', at: 'start' } }, hide: ['keyboard'], }) } }} // Start from your own layout instead of the default. config={{ ui: { layout: withLayout({ hide: ['geojson'] }, adminLayout) } }} ``` - **`move`** puts a control in a slot, wherever it was before, or adds it if it wasn't placed. It goes at the end of the slot (farthest from the slot's edge), or first with `{ slot, at: 'start' }`. Moving a control out of a group leaves the rest of the group where it is. To build a new group, write that slot out in full. - **`hide`** takes controls off the layout and wins over `move`. It only removes the button: the feature stays reachable by keyboard shortcut. To turn the feature off, use its flag (`dataTable: false`, `geojsonEditor: false`, …). The search box and the drawing tools live inside `'toolbar'`; choose them with `config.tools`. - The slots each control may move to are typed: `move: { toolbar: 'statusLeft' }` or `move: { attribution: 'topLeft' }` doesn't compile. Spreading `{ ...DEFAULT_LAYOUT, topRight: ['table'] }` lists the table twice (in `topRight` and in the default `bottomLeft`). The [first place in slot order](https://elementeditor.dev/docs/guides/configuring-layout.md#entries) wins, so whether the table moves depends on the slots. That's why it logs a development warning that points to `withLayout`. --- ## Entries | Id | Control | |---|---| | `'toolbar'` | The drawing toolbar (tools + place search) | | `'undo'`, `'redo'` | Undo and redo buttons | | `'fitBounds'` | Zoom to all features (or to the selection) | | `'locate'` | Show my location | | `'zoomIndicator'` | Zoom level (click to type one) | | `'table'` | Show or hide the data table | | `'schema'` | Edit schema | | `'geojson'` | Show GeoJSON | | `'settings'` | Editor settings | | `'keyboard'` | Keyboard shortcuts | | `'applyChanges'` | "Apply changes" button (needs `onSubmit`) | | `'basemap'` | Basemap picker (first in the default `bottomLeft`). Only shown when the editor has a picker: always on the MapLibre drop-in unless `basemaps={false}`, on the Leaflet drop-in only with two or more `basemaps`. See [Basemaps](https://elementeditor.dev/docs/guides/basemaps.md) | | `'attribution'` | Map tile and data credits (status bar only) | | `'separator'` | A thin divider line (inside a group, or in the status bar) | | `{ group: [...] }` | Several controls joined in one pill | Types: `LayoutConfig` (a map slot takes `MapSlotConfig`, a status slot `StatusSlotConfig`), `MapSlot` / `StatusSlot` / `LayoutSlot`, `LayoutControl`, `MapEntry` / `StatusEntry` / `LayoutEntry`, `MapGroup` / `StatusGroup` / `LayoutGroup`, `LayoutPatch`. Each slot only accepts the entries it can show, so the rules below are compile errors in TypeScript. If you build a layout in a variable, annotate it (`const layout: LayoutConfig = …`) or write `… satisfies LayoutConfig` so the strings stay literal types. **Rules** (from JavaScript, broken ones are skipped with a warning in development): - **One place per control.** A control listed twice stays at its first place, reading the slots in the order `topLeft`, `topCenter`, `topRight`, `leftCenter`, `rightCenter`, `bottomLeft`, `bottomCenter`, `bottomRight`, `statusLeft`, `statusRight`. - `'toolbar'` can't go in the status bar or in a group. - `'basemap'` can't go in a group. When the editor has no basemap picker the entry is simply not rendered. - `'applyChanges'` can't go in the status bar. - `'attribution'` can only go in `statusLeft` / `statusRight`. - Groups can't contain groups. - `'separator'` goes inside a group or in a status slot; directly in a map slot it's dropped (put it inside a `{ group: [...] }`). - A status slot is always an array (the status bar is horizontal); `{ items, direction }` is for map slots. **Nothing out of reach.** In development the editor also warns once when a layout hides something people need: no `'toolbar'` while drawing is possible (the tools are then reachable only by shortcut; set `readonly` or `tools: []` if that's on purpose), no `'applyChanges'` while `onSubmit` is set, or no undo/redo while keyboard shortcuts are off. Turning a control off with its flag never warns. ### Groups `{ group: ['table', 'schema', 'geojson'] }` draws the buttons in one joined pill, like the drawing toolbar. A group follows its slot's direction (vertical in `leftCenter` / `rightCenter` by default). A `'separator'` inside a group draws a divider line in the pill. A group of one button is fine. In the status bar a group is a tight cluster of small icons with no gaps. ### Separators `'separator'` can appear any number of times inside groups and in the status bar slots. It needs a surface to draw on, so a separator directly in a map slot (over the map tiles) is dropped with a warning in development; to divide buttons on the map, put them in a group: `bottomLeft: [{ group: ['table', 'separator', 'schema'] }]`. Separators at the start or end, next to each other, or next to a hidden control are dropped, so hiding a button never leaves a stray line. ### Visibility flags still apply `layout` decides *where*; the usual flags decide *whether*: `zoomToAll`, `locateButton`, `zoomIndicator`, `dataTable`, `schemaEditor`, `geojsonEditor`, `settings`, `keyboardShortcuts.show`. Schema and "Apply changes" are hidden while `readonly`, and "Apply changes" needs `onSubmit`. A group whose buttons are all hidden disappears. Undo and redo keyboard shortcuts (Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z) keep working whether or not the buttons are placed. ### Starting with the GeoJSON inspector open `ui.geojsonEditorOpen: true` (or `'docked'`, which now means the same) opens the inspector when the editor mounts, which suits demos and embeds that show the data next to the map. It opens in the visitor's last mode: docked on the right by default, or as a floating window once they have undocked it. ```tsx ``` It is a starting state: the visitor can close or undock it, and a reload opens it again. Once a visitor has clicked Dock / Undock, their saved choice wins. Opening on load doesn't move keyboard focus into the inspector, and the controls clear the dock from the first paint. With `geojsonEditor: false` it stays closed. With an adapter, set it on `` and render `GeoJSONModal` while `codeModalOpen` is true, with `}>`. --- ## Status bar Put anything in `statusLeft` or `statusRight` and a thin full-width bar appears under the map, with those controls drawn as small icons. It keeps the map free of less important buttons. ```tsx ``` - The bar sits **below** the map, so the map, data table and layers panel get shorter by its height (28px) instead of being covered. It stays visible when the data table is full screen. - If every control in the bar is hidden (say it only holds `'schema'` and the editor is `readonly`), the bar isn't rendered and the map gets the space back. - **Map attribution.** The credits (the active basemap's, the services in use (Nominatim while search is offered, OpenRouteService while routing through it), the map library's own on Leaflet, and anything your tile layer or `addAttribution` adds) normally sit in the bottom-right corner of the map: expanded at load, then folded behind a round "i" button on the first map interaction or after five seconds ([Basemaps → Attribution](https://elementeditor.dev/docs/guides/basemaps.md#attribution)). It is the first entry of the `bottomRight` slot (at the corner, before your own `bottomRight` entries), so when it expands the bottom row wraps around it instead of covering it. `'attribution'` in a status slot moves them into the bar as one line of small grey text with working links; if it doesn't fit it ends in "…" and shows the full text on hover. **When you don't list `'attribution'`, it stays on the map** — attribution is usually a license requirement, so it's never silently removed. --- ## Custom buttons via slots Need an "Admin" button? Pass JSX through the `slots` prop. Each of the eight map slots (`slots.topLeft` … `slots.bottomRight`) renders your node at the start of that slot, before the built-in entries. The status bar slots take no JSX. `slots` also has `mapOverlay` (a full-map layer), `panelFooter` (under the layers panel) and `toolbar` (unpositioned, in the map area). ```tsx import { ElementEditor, IconButton } from '@element-editor/react' import { Gear } from '@phosphor-icons/react' ), }} /> ``` `IconButton` is the 48×48 card all built-in map buttons use (same style, tooltip, active/hover/focus/disabled states). --- ## Floating toolbar direction Where the toolbar sits is a layout slot. How its tools are laid out inside is `config.toolbar.direction`: ```tsx config={{ toolbar: { direction: 'vertical' }, // stack tools top to bottom ui: { layout: withLayout({ move: { toolbar: { slot: 'leftCenter', at: 'start' } } }) }, }} ``` In `vertical` mode the search input collapses to a magnifying-glass button whose popup opens beside the toolbar (away from the map edge it's on). --- ## Styling hooks - `[data-elm-slot="bottomLeft"]` (and every other slot name) — the slot's container. - `[data-elm-group]` — a group; `[data-elm-separator]` — a separator. - `[data-elm-status-bar]` — the status bar. --- ## Worked example — a "viewer with admin tools" layout Viewers see the map and the basemap picker; admins also get the table and schema editor (bottom-right, vertical); super-admins get the GeoJSON inspector and the apply button (top-right). ```tsx import { ElementEditor, type LayoutConfig } from '@element-editor/react' const layout: LayoutConfig = { topCenter: ['toolbar'], topLeft: ['basemap', 'fitBounds', 'zoomIndicator'], leftCenter: [{ group: ['undo', 'redo'] }], ...(role !== 'viewer' && { bottomRight: { items: [{ group: ['table', 'schema'] }], direction: 'vertical' } }), ...(role === 'super' && { topRight: ['geojson', 'applyChanges'] }), statusRight: ['attribution'], } ``` --- ## Adapter-only setups `ui.layout` is for ``. With `@element-editor/adapter-leaflet` / `adapter-maplibre` and `ElementEditorUIProvider` you compose the UI yourself; put `UndoRedoToolbar` (or `UndoButton`, `RedoButton` inside a `ControlGroup`), `FloatingToolbar` and the buttons wherever you like. A standalone `FloatingToolbar` reads its position from the toolbar's layout slot (`ui.layout: { bottomRight: ['toolbar'] }`). --- ## What's next - [Reference: ElementEditorConfig](https://elementeditor.dev/docs/reference/element-editor-react.md#elementeditorconfig) — the full config type - [Custom UI with adapters](https://elementeditor.dev/docs/guides/custom-ui-with-adapters.md) — building a fully custom layout on `@element-editor/adapter-leaflet`/`maplibre` - [Theming](https://elementeditor.dev/docs/guides/theming.md) — recoloring the editor to match your product --- # Basemaps *Built-in basemaps, a picker, and your own styles.* The MapLibre drop-in (`@element-editor/react`) ships with five basemaps and a picker. Adapters let you reuse the same catalog on your own map. The Leaflet drop-in supports raster basemaps only. --- ## Built-in basemaps | id | Kind | Look | |---|---|---| | `streets` | vector | OpenFreeMap Streets, with Mapterhorn hillshade | | `terrain` | vector | terrain-oriented style with Mapterhorn hillshade | | `light` | vector | muted light style, so your data stands out | | `dark` | vector | dark style | | `osm` | raster | standard OpenStreetMap tiles | | `'auto'` | | not a basemap: resolves to `streets` in a light editor and `dark` in a dark editor, and switches live when the theme changes | All vector basemaps use OpenFreeMap tiles (no API key). `'auto'` is the default. ```tsx import { ElementEditor } from '@element-editor/react' import '@element-editor/react/style.css' ``` If a basemap's style can't be loaded (network down, bad style URL), the drop-in still mounts on a blank map (or keeps the previous basemap) and reports the error with `source: 'basemap'` (`onError` / `onEvent` / toast). `defaultBasemap` is the **starting** choice. The picker (bottom-left by default) lets users switch, and their pick is remembered in `localStorage` (`elm_basemap`, or `elm__basemap` with [`config.persistKey`](https://elementeditor.dev/docs/guides/persisting-data.md#elements-own-saved-state-persistkey--persist)) and wins over `defaultBasemap` on the next load. Use `basemaps` to change what the picker offers, or `basemaps={false}` to hide it. ```tsx // fewer choices // no picker ('auto') ``` ### Controlling the basemap from your app Pass `basemap` to own the choice: the map shows it, and changing it switches the basemap. `onBasemapChange` tells you when the user picks another one (or you call `ref.setBasemap()`); update `basemap` there, or the picker can't change anything (a dev-mode warning says so). ```tsx const [basemap, setBasemap] = useState(() => loadFromProfile() ?? 'auto') { setBasemap(b); saveToProfile(b) }} /> ``` - A controlled editor reads and writes **no** `localStorage`: you decide what's remembered. - `onBasemapChange` gets the entry as it appears in `basemaps`: `'auto'` stays `'auto'` (resolve it with `resolveBasemap(b, theme)` from `@element-editor/adapter-maplibre/basemaps`). It is not called when `'auto'` follows a theme change, nor when you change `basemap`. - `basemap` doesn't have to be in `basemaps`: it is applied and the picker shows none selected. With `basemaps={false}` it simply fixes the basemap. - Custom entries are compared by `id` (then `label`, then URL). Give a style object an `id` or keep it stable: an id-less object created inline counts as a new basemap on every render (dev-mode warning). - Don't call `map.setStyle()` yourself on a controlled editor: Element Editor doesn't know about that style, and setting `basemap` to the value it already has does nothing. Switch with the prop. Without owning the state, `ref.getBasemap()` returns the current choice and `ref.setBasemap(b)` switches like a user pick, except that it isn't remembered for the next visit. The picker is the `'basemap'` layout control. It is hidden whenever the editor has no picker, can't be put in a group, and can be moved like any other control; see [Configuring layout](https://elementeditor.dev/docs/guides/configuring-layout.md). --- ## Custom basemaps Anything in `basemap` / `defaultBasemap` / `basemaps` can be a custom entry: ```tsx ``` | Shape | Fields | |---|---| | Vector style | `{ style: string \| StyleSpecification, id?, label?, thumbnail? }` | | Raster tiles | `{ url, attribution, maxZoom?, id?, label?, thumbnail? }` (256px XYZ; `maxZoom` defaults to 19) | `id` identifies the entry: the picker tells entries apart by it and the user's pick of a custom entry is remembered only when it has one. Without an `id`, the entry falls back to its `label`, then its URL; two style objects with neither can't be told apart, so give every custom entry a unique `id` (a dev-mode warning says so). `label` is the text shown in the picker. Built-in ids, `'auto'` and custom entries with an `id` are remembered. Element's own layers (features, drawing, snapping) are kept when the basemap changes, so you can switch styles at any time without losing edits. A custom style should not use layer or source ids starting with `elm-`, which Element reserves. --- ## Attribution Credits are shown in the map's attribution control and must stay visible. The built-ins require: - **OpenFreeMap vector basemaps** (`streets`, `terrain`, `light`, `dark`): OpenFreeMap, © OpenMapTiles, and Data from © OpenStreetMap contributors. Added automatically. - **Hillshade (`streets`, `terrain`)**: © Mapterhorn (links to mapterhorn.com/attribution). Added automatically. - **`osm`**: © OpenStreetMap contributors. Added automatically. Respect the [OSM tile usage policy](https://operations.osmfoundation.org/policies/tiles/); heavy production traffic should use your own tile provider (`config.network.osmRaster`). - **Swapped servers** (`config.network`): give each source's `attribution`; without one Element drops the default provider's credit, keeps the OpenStreetMap data credit for vector and OSM raster tiles, and logs a development warning. For custom basemaps, pass `attribution` (raster) or include it in your style's sources (vector). **How the drop-in shows it.** Both drop-ins (MapLibre and Leaflet) follow the [OSM Foundation attribution guidelines](https://osmfoundation.org/wiki/Licence/Attribution_Guidelines), at every width: - At load the credits are **expanded**, visible without any click, at the start of the `bottomRight` slot (the bottom row wraps around them). - They **collapse to a round "i" button** on the first map interaction (pan, click, zoom, keyboard) or after **five seconds**, whichever comes first. The timer only counts while the page is visible. Nothing animates, so `prefers-reduced-motion` needs no special case. - The "i" button opens them again at any time; once you open them yourself no timer closes them (a map drag does, and on Leaflet so does `Escape`). - With `'attribution'` in a status slot ([Configuring layout](https://elementeditor.dev/docs/guides/configuring-layout.md)) the credits are a full line in the status bar instead and never collapse. If you add your own sources or layers (`onMapReady`, `mapOptions`, a custom `tileLayer`, or your own map with an adapter), give each one its `attribution` so its credit appears in the same control, and keep that control visible: hiding or covering it breaks most data licences, OpenStreetMap's ODbL included. With an adapter you own the map, so its attribution control (and how it collapses) is yours to keep compliant. --- ## Self-hosting the tiles, fonts and sprite The built-in vector styles load tiles and glyphs (fonts) from OpenFreeMap, hillshade elevation from Mapterhorn, and a small sprite (custom icons OpenFreeMap doesn't have) from jsDelivr at the installed package version (`https://cdn.jsdelivr.net/npm/@element-editor/adapter-maplibre@/basemaps/sprite`). `config.network` points each at your own server or provider: ```tsx ``` For the sprite, copy the `sprite*.json` / `sprite*.png` files from `node_modules/@element-editor/adapter-maplibre/basemaps/` to a folder you serve and pass its **absolute** URL prefix (without extension); MapLibre can't resolve a relative one. Vector tiles must use the OpenMapTiles schema, glyphs must include Noto Sans Regular / Bold / Italic, and elevation is terrarium-encoded unless you set `encoding`. Headers go through `mapOptions.transformRequest`. All the rules, plus the Picker, routing and search servers: [Third-party services and self-hosting](https://elementeditor.dev/docs/guides/third-party-services.md). --- ## With the MapLibre adapter On your own MapLibre map, use the catalog from `@element-editor/adapter-maplibre/basemaps` and the `BasemapControl` picker from the main entry. `maplibre-gl` is a peer dependency. ```tsx import { ElementEditorControls, BasemapControl } from '@element-editor/adapter-maplibre' import { loadBasemapStyle } from '@element-editor/adapter-maplibre/basemaps' ``` - **`BasemapControl`** renders the picker and applies the choice with `setBasemap`. Props: `map?` (defaults to the surrounding `ElementEditorControls`' map), `basemaps?`, `value?`, `defaultValue?` (`'auto'`), `onChange?`, `storageKey?` (persist the choice in `localStorage` under this key, namespaced by `config.persistKey`) and `initialApplied?` (set when your map was created with the initial basemap's style already). On your own map it **leaves your style alone until there is a real choice**: with no `value`, no explicit `defaultValue` and nothing remembered under `storageKey`, the picker shows `'auto'` selected but applies nothing until the user picks. Pass `defaultValue` (or `value`) to apply a basemap on mount. `'auto'` follows the theme only while the control is mounted. - **`useBasemap(map, basemap, { theme, initialApplied? })`** is the hook `BasemapControl` applies with. Call it in an always-mounted component (and give `BasemapControl` `value`/`onChange` but no `map`) to keep `'auto'` following the theme while the picker is hidden; the drop-in does this. - **`setBasemap(map, input, { theme?, network? })`** loads and applies a basemap, preserving Element's layers and images and your own sources and layers (everything that wasn't part of the previous basemap, in its order relative to Element's layers, above the new basemap). Images you added with `map.addImage` are not kept: re-add them on `style.load`. The latest call wins. The basemap Element replaces is the style the map had when `ElementEditorControls` initialised (or the last one `setBasemap` applied), so on your own map add your layers after that (e.g. in `onReady`). - **Your own `map.setStyle()`** (your own switcher, MapTiler SDK style switching) works too: Element puts its own sources, layers and images back on top by itself. Your layers are yours to restore: re-add them from a `style.load` listener added in `onReady`, which runs after Element's repair. - **`loadBasemapStyle(input, { theme?, network? })`** resolves an input to a style (use it for `new maplibregl.Map({ style })`). `network` is the tile part of `config.network` (`vectorTiles`, `dem`, `osmRaster`, `glyphs`, `sprite`); `BasemapControl` and `useBasemap` pass the editor's own. - **`resolveBasemap(input, theme)`** resolves `'auto'` to `'streets'` or `'dark'`. - **`BASEMAPS`** lists the built-ins (`id`, `label`, `kind`, `thumbnail`). Thumbnails are small inlined WebP images, so opening the picker makes no requests. - **`BasemapInput`** is the type of every entry above. ```tsx import { setBasemap } from '@element-editor/adapter-maplibre/basemaps' map.on('load', () => setBasemap(map, 'terrain')) ``` Put `BasemapControl` inside your own layout, or with the full UI stack render it in the `'basemap'` layout slot. The catalog is lazy-loaded: importing `BasemapControl` doesn't pull in the style JSON until it's needed. --- ## Leaflet: raster basemaps The Leaflet drop-in (`@element-editor/react/leaflet`) has no vector basemaps. By default it shows OpenStreetMap with no picker (`config.network.osmRaster` serves it from your own tile server). Pass `basemaps` to choose the raster layer (a single entry just replaces OpenStreetMap; two or more add a picker), or `tileLayer` for full control. `tileLayer` wins and disables the picker. ```tsx import { ElementEditor } from '@element-editor/react/leaflet' import '@element-editor/react/leaflet/style.css' ``` The first entry is the default (or pass `defaultBasemap`) and the user's pick is remembered (`localStorage` key `elm_basemap_leaflet`). Entries are told apart by `id`, else by `url`. `basemap` + `onBasemapChange` and `ref.getBasemap()` / `ref.setBasemap()` work as on the MapLibre drop-in ([Controlling the basemap](https://elementeditor.dev/docs/guides/basemaps.md#controlling-the-basemap-from-your-app)); values are `basemaps` entries or `'osm'`, and the controlled basemap may be any raster entry, listed or not. `tileLayer` overrides all of these (dev-mode warning). ### `tileLayer` (any react-leaflet tile component) ```tsx import { TileLayer } from 'react-leaflet' import { ElementEditor } from '@element-editor/react/leaflet' } /> ``` `tileLayer` accepts any `React.ReactNode` rendered inside the editor's `MapContainer` (``, ``, third-party tile components). To swap it at runtime, give the layer a `key` that changes with the style, otherwise Leaflet may keep the old tile cache. ### Common raster providers Replace keys with your own and check each provider's terms. | Provider | URL template | Notes | |---|---|---| | OpenStreetMap | `https://tile.openstreetmap.org/{z}/{x}/{y}.png` | built in as `'osm'` | | Esri imagery | `https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}` | `Tiles © Esri`; commercial use needs an ArcGIS plan | | MapTiler | `https://api.maptiler.com/maps/streets-v2/{z}/{x}/{y}.png?key=KEY` | key required; for MapTiler vector styles use the MapLibre drop-in | | Mapbox | `https://api.mapbox.com/styles/v1/mapbox/streets-v12/tiles/{z}/{x}/{y}?access_token=TOKEN` | with `tileSize={512}` and `zoomOffset={-1}` on a ``; for vector use the MapLibre drop-in | | Stadia Maps | `https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png` | free for non-commercial | --- ## Adapters on a Leaflet map `@element-editor/adapter-leaflet` plugs into your own `MapContainer`, so you control tiles with your own ``. The basemap catalog and `BasemapControl` are MapLibre-only. --- ## What's next - [Reference: ElementEditorProps](https://elementeditor.dev/docs/reference/element-editor-react.md#elementeditorprops) — full prop list - [Configuring layout](https://elementeditor.dev/docs/guides/configuring-layout.md) — placing the `'basemap'` control - [Theming](https://elementeditor.dev/docs/guides/theming.md) — recoloring the editor chrome to match your basemap - [Choosing a package](https://elementeditor.dev/docs/introduction/choosing-a-package.md) — when to use `@element-editor/react` vs an adapter --- # Third-party services and self-hosting Out of the box Element Editor talks to free public services: basemap tiles, fonts and elevation from OpenFreeMap and Mapterhorn, OpenStreetMap raster tiles, the Picker's Overpass lookups, the Route tool's router and the search box's geocoder. That works for a demo. For production, privacy, an intranet or a paid plan you usually want your own servers or keys. `config.network` sets all of them in one place: ```tsx ``` The settings belong to that editor: two editors on one page can use different servers and keys. Leave a key out to keep the default service. Set a service to `false` to turn it off: the tool or box that needs it is hidden. The same `config` works with the adapters: pass it to `ElementEditorUIProvider` (or `ElementEditorConfigProvider`) around your `ElementEditorControls`. --- ## What Element calls | Service | Default | `config.network` key | Auth | Licence and attribution | |---|---|---|---|---| | Vector tiles (Streets, Terrain, Light, Dark) | OpenFreeMap `tiles.openfreemap.org/planet` | `vectorTiles` | Key in the URL if your provider needs one | OpenFreeMap, © OpenMapTiles, © OpenStreetMap contributors. Must be the **OpenMapTiles schema** (the built-in styles and the Picker read its layers). | | Glyphs (map fonts) | OpenFreeMap fonts | `glyphs` | Key in the URL | Must serve **Noto Sans Regular, Bold and Italic** (the styles ask for these). | | Sprite (map icons) | jsDelivr copy of `@element-editor/adapter-maplibre/basemaps/sprite` | `sprite` | none | Element's own files (MIT). | | MapLibre worker (MapLibre drop-in, MapLibre GL JS 6 only) | jsDelivr copy of the installed `maplibre-gl/dist/maplibre-gl-worker.mjs` | `maplibreWorker` | none | MapLibre GL JS (BSD-3-Clause). See [below](https://elementeditor.dev/docs/guides/third-party-services.md#maplibre-gl-js-6-worker-maplibreworker). | | Elevation (hillshade on Streets / Terrain) | Mapterhorn `tiles.mapterhorn.com` | `dem` | Key in the URL | © Mapterhorn. **Terrarium** encoding, 512 px tiles; set `encoding` for another one. | | OSM raster (`'osm'` basemap, both engines) | `tile.openstreetmap.org` | `osmRaster` | Key in the URL (Leaflet loads tiles as images: no headers) | © OpenStreetMap contributors. The [tile usage policy](https://operations.osmfoundation.org/policies/tiles/) rules out heavy production use. | | Overpass (Picker) | `overpass-api.de` | `overpass` | via `fetch` | OSM data, [ODbL](https://www.openstreetmap.org/copyright). The public server is often busy. | | Routing (Route tool) | **OSRM demo** `router.project-osrm.org` | `routing` | ORS key as the `Authorization` header | ORS: "© openrouteservice.org by HeiGIT" (shown automatically). See below. | | Geocoding (search box) | Nominatim `nominatim.openstreetmap.org` | `nominatim` | via `fetch`; `email` as a query parameter | "Geocoding by Nominatim" (shown automatically). [Usage policy](https://operations.osmfoundation.org/policies/nominatim/): at most 1 request/s, no heavy use. | The editor makes no other requests (`fetchSheetCsv` in `@element-editor/core` fetches a Google Sheet only when your code calls it). > **The default router is a demo.** Without `routing` set, the Route tool snaps through the public OSRM demo server. It is **car-only** (the walking profile in the URL is ignored), rate-limited and not for production. Element logs a development warning the first time it uses it. For production set an OpenRouteService key (`routing: { apiKey }`, free key at [openrouteservice.org](https://openrouteservice.org/dev/#/signup)) or your own server (`routing: { url }`). --- ## MapLibre GL JS 6 worker: `maplibreWorker` MapLibre GL JS 5 has its worker built in. Version 6 loads it from a separate file, `maplibre-gl-worker.mjs`, and bundlers (Vite, webpack, Turbopack) don't put that file where MapLibre looks for it. So before the MapLibre drop-in creates its map on MapLibre 6, it passes `network.maplibreWorker` to MapLibre's `setWorkerUrl`. By default that is the jsDelivr copy of the version you installed (`https://cdn.jsdelivr.net/npm/maplibre-gl@/dist/maplibre-gl-worker.mjs`). To serve the worker yourself (offline, intranet, strict CSP), point `maplibreWorker` at your copy. With Vite: ```ts import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url' network: { maplibreWorker: workerUrl } ``` With webpack 5 (Next.js): `maplibreWorker: new URL('maplibre-gl/dist/maplibre-gl-worker.mjs', import.meta.url).toString()`. See MapLibre's [installation notes](https://maplibre.org/maplibre-gl-js/docs/) for other bundlers. - `maplibreWorker: false`: the editor never calls `setWorkerUrl`. Your app sets it itself. - If your app has already called `setWorkerUrl`, the editor leaves that URL alone, whatever `maplibreWorker` says. - MapLibre has one worker URL per page, so with several editors the first one to create its map sets it. - On MapLibre 5 the setting is ignored (the worker is built in, nothing is requested). The adapters never create a map, so with `@element-editor/adapter-maplibre` on MapLibre 6 your own map setup calls MapLibre's `setWorkerUrl`, as MapLibre's docs describe. --- ## Map tiles: `vectorTiles`, `dem`, `osmRaster`, `glyphs`, `sprite` These rewrite the built-in basemaps (MapLibre drop-in, `BasemapControl`, `loadBasemapStyle` / `setBasemap`; on the Leaflet drop-in only `osmRaster` applies). A tile source is either: - a **URL**: a tile template (with `{z}`) or a TileJSON URL, or - an **object** of MapLibre source fields merged over the built-in source: `tiles`, `url`, `attribution`, `encoding`, `tileSize`, `maxzoom`, … ```ts network: { vectorTiles: 'https://tiles.example.com/planet.json', // TileJSON dem: { tiles: ['https://dem.example.com/{z}/{x}/{y}.png'], encoding: 'mapbox', attribution: '© Example' }, osmRaster: { tiles: ['https://osm.example.com/{z}/{x}/{y}.png'], attribution: '© OpenStreetMap contributors' }, glyphs: 'https://fonts.example.com/{fontstack}/{range}.pbf', sprite: `${location.origin}/map/sprite`, } ``` The tile URLs are read when a basemap loads, so a change applies on the next basemap switch. `glyphs` and `sprite` must be absolute URLs (MapLibre can't resolve relative ones). To self-host the sprite, copy `sprite*.json` / `sprite*.png` from `node_modules/@element-editor/adapter-maplibre/basemaps/` to a folder you serve and pass its URL prefix without extension. **Headers for map resources** (a bearer token, a signed URL): use MapLibre's own `transformRequest` in the drop-in's `mapOptions`. It covers every tile, glyph and sprite request MapLibre makes: ```tsx ({ url, headers: { Authorization: `Bearer ${token}` } }) }} /> ``` Custom basemaps (`{ style }` / `{ url }` entries) are yours already: `config.network` doesn't touch them. --- ## Services: `overpass`, `routing`, `nominatim`, `fetch` ```ts network: { overpass: { endpoint: 'https://overpass.example.com/api/interpreter', timeoutMs: 10_000 }, routing: { apiKey: ORS_KEY }, // OpenRouteService // routing: { url: 'https://osrm.example.com/route/v1/foot' }, // your own OSRM (provider 'osrm' when there's no key) // routing: { provider: 'ors', url: 'https://ors.example.com/ors/v2/directions/foot-walking/geojson' }, // self-hosted ORS, no key nominatim: { url: 'https://geocode.example.com/search', email: 'maps@example.com' }, fetch: (input, init) => fetch(input, { ...init, headers: { ...init?.headers, 'X-Api-Key': KEY } }), } ``` - **`overpass`**: `endpoint` (default `https://overpass-api.de/api/interpreter`) and `timeoutMs` per attempt (default 15000). - **`routing`**: `provider` (`'ors'` when `apiKey` is set, else `'osrm'`), `url` (ORS: the directions endpoint; OSRM: the route service prefix including the profile, Element appends `/{lng,lat;…}?overview=full&geometries=geojson`), `apiKey`, `attribution`. - **`nominatim`**: `url` (any Nominatim-compatible `/search`; extra query parameters in it are kept), `email` (sent as the `email` parameter, as Nominatim's policy asks of heavy users), `attribution`. - **`fetch`** is used for every request Element makes itself: Overpass, routing and search. Use it for a proxy, auth headers, logging or tests. It can be an inline function. To call the services yourself, `fetchRoute(waypoints, { provider, url, apiKey, fetch, signal })` and `fetchOverpassFeatures(lat, lon, radius, click, { endpoint, timeoutMs, fetch, signal })` (`@element-editor/core`) take the same settings. --- ## Turning services off | Setting | Effect | |---|---| | `overpass: false` | The Picker uses only the basemap's vector tiles (MapLibre with an OpenMapTiles basemap) and says "No shape here in the basemap" where they have nothing. On Leaflet (no vector tiles) the Picker is hidden. | | `routing: false` | The Route tool is hidden (toolbar, shortcut, `ref.setTool('route')`). | | `nominatim: false` | The search box is hidden and the Nominatim credit dropped. | For a fully offline or intranet editor, also give it basemaps you serve (`vectorTiles` / `glyphs` / `sprite` / `dem`, your own `basemaps`, or `basemaps={false}`), or restrict `tools`. --- ## Content Security Policy (CSP) If your site sends a `Content-Security-Policy` header, the editor needs: | Directive | Allow | Why | |---|---|---| | `worker-src` (and `child-src` for older Safari) | `blob:` | MapLibre GL starts its workers from `blob:` URLs (on MapLibre 6 when `maplibreWorker` is on another origin, such as the jsDelivr default). Element's geometry worker (boolean operations, cut hole, slice, buffer / simplify / smooth previews) is inlined in the package and also starts from a `blob:` URL; only if creating that throws does it fall back to a `data:` URL. | | `style-src` | `'unsafe-inline'` | The editor and its libraries (toasts, the CodeMirror GeoJSON inspector) add `