Packages

MapLibre GL JS components for Phoenix LiveView. A declarative and reactive way to build interactive maps in Elixir.

Current section

Files

Jump to
maplibrex README.md
Raw

README.md

# MaplibreX

[![Hex.pm](https://img.shields.io/hexpm/v/maplibrex.svg)](https://hex.pm/packages/maplibrex)
[![Documentation](https://img.shields.io/badge/hexdocs-documentation-blue)](https://hexdocs.pm/maplibrex)
[![License](https://img.shields.io/hexpm/l/maplibrex.svg)](https://github.com/CountlinkX-Solutions/maplibrex/blob/main/LICENSE)

[MapLibre GL JS](https://maplibre.org/) as declarative Phoenix LiveView components.
Build interactive maps with assigns and `handle_event/3` instead of hand-written
JavaScript.

Inspired by [svelte-maplibre](https://github.com/dimfeld/svelte-maplibre).

```elixir
def render(assigns) do
  ~H"""
  <.map id="map" center={@center} zoom={@zoom} class="h-96 w-full" />
  <.navigation_control id="nav" map_id="map" position="top-left" />

  <.marker :for={city <- @cities} id={city.id} map_id="map"
           lng_lat={city.coords} color="#22d3ee" popup_text={city.name} />
  """
end

def handle_event("map:moved", %{"center" => center, "zoom" => zoom}, socket) do
  {:noreply, assign(socket, center: center, zoom: zoom)}
end

# Components given no `events` list push every event they emit, and the
# LiveView crashes on one it has no clause for: keep this catch-all last.
def handle_event(_event, _params, socket), do: {:noreply, socket}
```

## Why

- **Declarative** — components and assigns, not imperative JS glue.
- **Reactive** — the map follows your assigns; events flow back into `handle_event/3`.
- **Small** — the published bundle is about 88 KB (27 KB gzipped). MapLibre GL is a
  peer dependency, so there is never a second copy of it on the page.
- **Complete** — 32 components covering layers, sources, controls, 3D terrain,
  deck.gl and custom WebGL layers. A map can also open with a camera flight
  (`fly`), stay behind a loading curtain (`curtain`) until its first render
  is complete, and be drawn as a globe (`projection`).
- **Typed** — the hook layer is written in TypeScript, type-checked in CI.
- **Tested** — Elixir tests against the rendered component output, and
  vitest tests for the hooks against a MapLibre GL mock.

## Installation

Requires Elixir 1.15+ and Phoenix LiveView 1.0+. The steps below start from an
application generated by `mix phx.new` (Phoenix 1.8), which builds its
JavaScript with esbuild and its CSS with Tailwind.

### 1. Add the dependency

```elixir
def deps do
  [
    {:maplibrex, "~> 0.3.0"}
  ]
end
```

A GitHub dependency (`github: "CountlinkX-Solutions/maplibrex"`) lands in
`deps/maplibrex` like the Hex package, so the steps below apply as written. A
`path:` dependency is used where it is and never copied into `deps/`; steps 3
and 5 say what changes for it.

### 2. Install the JavaScript peer dependencies

MaplibreX does not bundle MapLibre GL — your application owns that version.

```bash
npm install --prefix assets maplibre-gl
```

This installs the latest release. Install `maplibre-gl@5` instead if you need
version 5; the table below says when.

Only if you plan to use `<.deckgl_layer>`:

```bash
npm install --prefix assets @deck.gl/core @deck.gl/layers \
                            @deck.gl/aggregation-layers @deck.gl/mapbox
```

If you skip them, step 3 adds the esbuild flag that lets the build succeed
without them.

#### Which MapLibre GL version?

MaplibreX supports `>=5.0.0 <7.0.0`.

| | maplibre-gl v5 | maplibre-gl v6 |
| --- | --- | --- |
| Every component except `deckgl_layer` | ✅ | ✅ |
| `<.deckgl_layer>` | ✅ | ❌ |
| Extra install step | none | serve the worker (step 4) |

deck.gl is the single exception: `@deck.gl/mapbox` reads MapLibre's internal
`map.transform`, which v6 removed. Every published version, including the 9.4
alphas, still does. If you use `<.deckgl_layer>`, pin `maplibre-gl` to
`^5.0.0`; MaplibreX raises a message saying exactly this rather than letting
deck.gl fail with an opaque error.

maplibre-gl v6 is published as ES modules only. That does not change how
`app.js` is loaded: esbuild bundles v6 into it like any other package, and the
generated `<script defer>` tag still loads it. What v6 needs in addition is its
worker file, served by your application (step 4).

### 3. Register the hooks

In `assets/js/app.js`, import the hooks and add them to the ones the generated
`LiveSocket` already has:

```javascript
import { MapHooks } from "maplibrex"

const liveSocket = new LiveSocket("/live", Socket, {
  longPollFallbackMs: 2500,
  params: {_csrf_token: csrfToken},
  hooks: {...colocatedHooks, ...MapHooks},
})
```

The bare `"maplibrex"` import resolves through `NODE_PATH`, which the generated
esbuild profile points at `deps/`, the same way Phoenix resolves `phoenix` and
`phoenix_live_view`. The MaplibreX bundle found there imports `maplibre-gl`,
which npm installed in `assets/node_modules`, and esbuild does not look in that
directory for code that lives under `deps/`. In `config/config.exs`, add it to
the `NODE_PATH` list of the esbuild profile, after the two entries already
there:

```elixir
    env: %{
      "NODE_PATH" => [
        Path.expand("../deps", __DIR__),
        Mix.Project.build_path(),
        Path.expand("../assets/node_modules", __DIR__)
      ]
    }
```

Without it the build stops with `Could not resolve "maplibre-gl"`. A list in
`env` needs version 0.10 or later of the `esbuild` package, which Phoenix 1.8
generates. Only the esbuild profile changes; the tailwind profile below it has
the same `NODE_PATH` line and keeps it.

If you did not install the deck.gl packages, also add `--external:@deck.gl/*`
at the end of the profile's `args`:

```elixir
    args:
      ~w(js/app.js --bundle ... --alias:@=. --external:@deck.gl/*),
```

MaplibreX imports deck.gl when a `<.deckgl_layer>` mounts, and esbuild
resolves that import at build time: with neither the packages nor this flag
the build stops with `Could not resolve "@deck.gl/core"`. With the packages
installed, leave the flag out; esbuild then includes deck.gl in `app.js`.

With a `path:` dependency there is no `deps/maplibrex` for `NODE_PATH` to find.
Import the bundle by its path instead, relative to `assets/js/app.js`. For
`{:maplibrex, path: "../maplibrex"}`:

```javascript
import { MapHooks } from "../../../maplibrex/priv/static/assets/js/maplibrex.js"
```

Keep the `assets/node_modules` entry in `NODE_PATH`: the bundle still imports
`maplibre-gl` from there.

### 4. maplibre-gl v6 only: serve the worker

Skip this step with maplibre-gl v5, which carries its worker inside its own
bundle.

maplibre-gl v6 starts its worker from a separate file, `maplibre-gl-worker.mjs`
(which, before 6.13, imports `maplibre-gl-shared.mjs`). esbuild does not copy
these files into your build, and from the `app.js` that the generated profile
builds, MapLibre cannot tell where they are. Without this step the map shows
only its background and no tile data; recent 6.x releases also log
`Worker failed to load`.

MaplibreX's `mix maplibrex.copy_worker` copies the files next to `app.js`. Add
it to the asset aliases in `mix.exs`, after esbuild:

```elixir
      "assets.build": ["compile", "tailwind my_app", "esbuild my_app", "maplibrex.copy_worker"],
      "assets.deploy": [
        "tailwind my_app --minify",
        "esbuild my_app --minify",
        "maplibrex.copy_worker",
        "phx.digest"
      ],
```

It copies `maplibre-gl-worker.mjs`, and `maplibre-gl-shared.mjs` when the
installed release has it, from `assets/node_modules/maplibre-gl/dist` to
`priv/static/assets/js` (`--from` and `--to` change those). With maplibre-gl
v5 it copies nothing and says so, so the aliases can keep it whichever version
you install.

Then point MapLibre at the copy, near the top of `assets/js/app.js`:

```javascript
import { getVersion, setWorkerUrl } from "maplibre-gl"

setWorkerUrl(`/assets/js/maplibre-gl-worker.mjs?v=${getVersion()}`)
```

Run `mix assets.build` now, and again after every install or upgrade of
maplibre-gl. `mix setup` and `mix assets.deploy` copy the files too;
`mix phx.server` rebuilds `app.js` on change but does not copy them. The `v`
parameter keeps browsers from using a worker cached from another MapLibre
release.

This is the setup MapLibre
[documents for esbuild](https://maplibre.org/maplibre-gl-js/docs/#installation):
copy the worker into the build and call `setWorkerUrl`. The URL is absolute
because the generated profile builds `app.js` as a classic script, where
`import.meta.url` is empty.

### 5. Import the stylesheet

In `assets/css/app.css`, after the `@import "tailwindcss"` line:

```css
@import "maplibre-gl/dist/maplibre-gl.css";
@import "../../deps/maplibrex/assets/css/maplibrex.css";
```

With a `path:` dependency, use its path relative to `assets/css/app.css`
instead: `../../../maplibrex/assets/css/maplibrex.css` for
`path: "../maplibrex"`.

`maplibrex.css` also draws the loading curtain of `<.map curtain>`: without
it, the curtain does not cover the map (see "Loading curtain" in the
`MaplibreX.Components.Map` documentation).

### 6. Import the components

```elixir
defmodule MyAppWeb.MapLive do
  use MyAppWeb, :live_view
  import MaplibreX.Components

  # ...

  # Catch-all: components push every event they emit unless given `events`.
  def handle_event(_event, _params, socket), do: {:noreply, socket}
end
```

Unless told otherwise, a component that emits events pushes every one of
them (see [Events](#events)) to the LiveView it is rendered in, also from
inside a LiveComponent, whether or not the LiveView handles them. A LiveView
with no `handle_event/3` clause that matches one of them crashes on the first
one: Phoenix raises `FunctionClauseError` (`UndefinedFunctionError` when the
LiveView defines no `handle_event/3` at all), the LiveView process exits, and
the browser reconnects to a new one, mounted from scratch, so the assigns are
lost. A plain `<.map>` pushes `map:loaded` as soon as it has loaded. This is a
known issue, tracked in
[#45](https://github.com/CountlinkX-Solutions/maplibrex/issues/45).

Either keep a catch-all clause like the one above as the last
`handle_event/3` clause, or give each component that emits events the list of
events you handle; it then pushes only those:

```heex
<.map id="map" center={@center} zoom={@zoom} class="h-96 w-full" events={["map:moved"]} />
```

```elixir
def handle_event("map:moved", %{"center" => center, "zoom" => zoom}, socket) do
  {:noreply, assign(socket, center: center, zoom: zoom)}
end
```

A component without `events` still pushes everything, so a LiveView that
renders one keeps the catch-all clause.

## Configuration

Optional defaults, in `config/config.exs`:

```elixir
config :maplibrex,
  default_style: "https://demotiles.maplibre.org/style.json",
  default_center: [0, 0],
  default_zoom: 10
```

A `<.map>` without `style`, `center` or `zoom` uses them.

To see MaplibreX's lifecycle logging in the browser console, set
`window.__MAPLIBREX_DEBUG__ = true` before the bundle loads, or pass
`debug={true}` to a `<.map>`: the logging is then on for the whole page while
that map is on it. Warnings and errors are always logged.

## Components

**Core** — `map`

**Overlays** — `marker`, `popup`

**Layers** — `geojson_layer`, `circle_layer`, `line_layer`, `fill_layer`,
`symbol_layer`, `heatmap_layer`, `fill_extrusion_layer`, `background_layer`,
`hillshade_layer`, `raster_layer`

**Sources** — `vector_tile_source`, `raster_tile_source`, `raster_dem_source`,
`image_source`, `video_source`

**Controls** — `navigation_control`, `scale_control`, `fullscreen_control`,
`geolocate_control`, `attribution_control`, `terrain_control`, `control`,
`control_button`, `control_group`, `zoom_range`

**3D & terrain** — `terrain`, `sky` (`sky` does not work yet:
[#14](https://github.com/CountlinkX-Solutions/maplibrex/issues/14))

**Advanced** — `deckgl_layer`, `custom_layer`

Every component is documented with attributes, events and examples on
[HexDocs](https://hexdocs.pm/maplibrex).

Components find their map through `map_id`, so they can sit anywhere in the
same LiveView as their `<.map>`, or be nested in it. The layer and source
components, `geojson_layer`, `custom_layer` and `terrain` can come before or
after their map and their source: each appears as soon as the map can take
it, follows its assigns, and comes back after a map style change. A layer or source component
whose id is already on the map, from the map style or your own code, takes
that layer or source over for its updates and leaves it on the map when it is
removed. The control components and `zoom_range` can also come before or
after their map, follow their assigns and, several in one corner, keep the
order of the template. Markers and popups too can come before or after
their map and follow their assigns; a map style change leaves them alone.
All of these also come back on a `<.map>` that is removed and rendered again
under the same id (behind `:if`, say). `sky` and `deckgl_layer` still have to
come after their map.

Content nested in `<.map>` is rendered right after the map element, not
inside it; see `MaplibreX.Components.Map` for how to put your own content on
the map.

## Events

Map events arrive in your LiveView as ordinary `handle_event/3` calls:

| Event | Payload |
| --- | --- |
| `map:loaded` | `%{"mapId" => id}` |
| `map:moved` | `%{"center" => [lng, lat], "zoom" => z, "bearing" => b, "pitch" => p}` |
| `map:clicked` | `%{"lngLat" => [lng, lat], "point" => [x, y]}` |
| `map:zoom_changed` | `%{"zoom" => z}` |
| `map:error` | `%{"error" => message}` |
| `marker:clicked` | `%{"markerId" => id, "lngLat" => [lng, lat]}` |
| `marker:drag_start` / `marker:dragging` / `marker:drag_end` | `%{"markerId" => id, "lngLat" => [lng, lat]}` |
| `layer:feature_clicked` / `layer:feature_mouseenter` / `layer:feature_mouseleave` | `%{"layer_id" => id, "feature" => feature}` (no `feature` on `mouseleave`) |

`map:moved` is debounced by 150 ms so continuous panning does not flood the
socket.

Every component that emits events takes an optional `events` list. Given one,
it pushes only the events named in it, and the others cost no round trip:
`<.map id="map" events={["map:moved", "map:clicked"]} />` pushes those two,
and `events={[]}` pushes none. Without it, the component pushes every event it
emits, so keep a catch-all `handle_event/3` clause (see
[Import the components](#6-import-the-components)). Each component's docs list
the events it emits.

Every `layer:*` event identifies its layer with `"layer_id"`. The same value is
also sent as `"layerId"`, kept for compatibility with code written against
`geojson_layer` in 0.1.0; prefer `"layer_id"` in new code.

## Controlling the map

Map commands are `Phoenix.LiveView.JS` structs, so they run entirely on the
client with no server round-trip:

```elixir
alias MaplibreX.Components.Map

<button phx-click={Map.fly_to("map", [-74.5, 40], 12)}>Fly to NYC</button>
<button phx-click={Map.zoom_in("map")}>Zoom in</button>
<button phx-click={Map.fit_bounds("map", [[-74, 40], [-73, 41]], padding: 50)}>Fit</button>
```

Available: `fly_to/4`, `jump_to/4`, `fit_bounds/3`, `set_style/2`, `zoom_in/1`,
`zoom_out/1`, `reset_north/1`.

The animations respect the visitor's `prefers-reduced-motion` setting: for a
visitor who asks for reduced motion, MapLibre moves the map at once instead.
Pass `essential: true` to `fly_to/4` or `fit_bounds/3` (or in the payload of
`map:fly_to` and `map:fit_bounds`, below) for an animation the visitor needs
to see.

### Commands pushed from the server

The same commands can be sent from the LiveView process with `push_event/3`:
`map:fly_to`, `map:jump_to`, `map:fit_bounds`, `map:set_style`,
`map:set_bearing`, `map:set_pitch`, `map:reset_north`, `map:zoom_in` and
`map:zoom_out`.

Without further information every `<.map>` on the page reacts. Add the map's
component id as `id` to the payload to address a single map; maps with a
different id ignore the event:

```elixir
# Only the map rendered with id="detail" flies.
push_event(socket, "map:fly_to", %{id: "detail", center: [-3.7, 40.4], zoom: 12})
```

`id` is optional, so payloads without it behave exactly as before.

## Demo

A Phoenix application with example pages built on MaplibreX:
**[maplibrex_demo](https://github.com/CountlinkX-Solutions/maplibrex_demo)**

## Development

```bash
mix setup          # deps + npm install
mix test           # Elixir tests
mix typecheck      # tsc --noEmit
(cd assets && npm test)  # hook tests (vitest)
mix ci             # format check, warnings-as-errors, credo, tests
mix assets.build   # development bundle
mix assets.watch   # rebuild on change
```

Publishing (the alias builds `priv/static` first — never run `mix hex.publish`
directly, or the package ships without its JavaScript):

```bash
mix publish
```

Run it in `:dev`: `hex.publish` builds the documentation, and `ex_doc` is a
dev-only dependency. The release bundle is built by its own esbuild profile,
so the output is identical whatever `MIX_ENV` is set to.

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md). Bug reports and pull requests are
welcome.

## License

MIT — see [LICENSE](LICENSE).