MaplibreX
MapLibre GL JS as declarative Phoenix LiveView components.
Build interactive maps with assigns and handle_event/3 instead of hand-written
JavaScript.
Inspired by svelte-maplibre.
def render(assigns) do
~H"""
<.map id="map" center={@center} zoom={@zoom} class="h-96 w-full" events={["map:moved"]} />
<.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
# The map pushes only the events its `events` attribute names.
def handle_event("map:moved", %{"center" => center, "zoom" => zoom}, socket) do
{:noreply, assign(socket, center: center, zoom: zoom)}
end
Why
- Declarative — components and assigns, not imperative JS glue.
- Reactive — the map follows your assigns; the events you ask for flow back
into
handle_event/3. - Small — the published bundle is about 120 KB (37 KB gzipped). MapLibre GL is a peer dependency, so there is never a second copy of it on the page.
- Complete — 36 components covering layers, sources, your own icons for
symbol layers, controls, drawing and editing shapes, 3D terrain and sky,
deck.gl, custom WebGL layers and flows (wind, ocean currents). 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
def deps do
[
{:maplibrex, "~> 0.7.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.
npm install --prefix assets maplibre-gl
This installs the latest release. Install maplibre-gl@5 instead if your
application needs version 5; MaplibreX works with both.
Only if you plan to use <.deckgl_layer>, deck.gl 9.4 or later:
npm install --prefix assets @deck.gl/core @deck.gl/layers \
@deck.gl/aggregation-layers @deck.gl/maplibre
If you skip them, step 3 adds the esbuild flag that lets the build succeed without them.
Only if you plan to use <.draw>, Terra Draw and its MapLibre adapter, for
the hook step 3 adds from maplibrex/draw:
npm install --prefix assets terra-draw terra-draw-maplibre-gl-adapter
An application that does not draw installs neither, and needs no flag for
them: only maplibrex/draw imports Terra Draw.
Which MapLibre GL version?
MaplibreX supports >=5.0.0 <7.0.0.
| maplibre-gl v5 | maplibre-gl v6 | |
|---|---|---|
| Every other component | ✅ | ✅ |
<.deckgl_layer> |
✅ | ✅ 6.9.1 or later |
| Extra install step | none | serve the worker (step 4) |
<.deckgl_layer> draws with MapLibreOverlay from @deck.gl/maplibre, which
deck.gl 9.4 added for maplibre-gl 5 and 6. With maplibre-gl 6, use 6.9.1 or
later: before it, the MapLibre layers drawn after a deck.gl layer, such as the
basemap labels above a layer given before_id, can change size or disappear
(visgl/deck.gl#10700, fixed
in maplibre-gl 6.9.1). Without @deck.gl/maplibre, or with a deck.gl older
than 9.4, the layer reports an error that names the packages to install.
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:
import { MapHooks } from "maplibrex"
const liveSocket = new LiveSocket("/live", Socket, {
longPollFallbackMs: 2500,
params: {_csrf_token: csrfToken},
hooks: {...colocatedHooks, ...MapHooks},
})
MapHooks adds these keys to hooks, one for each hook a component names
in its phx-hook attribute:
AttributionControlHook, BackgroundLayerHook, CircleLayerHook,
ControlButtonHook, ControlGroupHook, ControlHook, CustomLayerHook,
DeckGlLayerHook, FillExtrusionLayerHook, FillLayerHook,
FlowLayerHook, FullscreenControlHook, GeoJSONLayerHook,
GeolocateControlHook, HeatmapLayerHook, HillshadeLayerHook,
ImageHook, ImageSourceHook, LineLayerHook, MapHook, MarkerHook,
NavigationControlHook, PopupHook, RasterDEMSourceHook,
RasterLayerHook, RasterTileSourceHook, ScaleControlHook, SkyHook,
SymbolLayerHook, TerrainControlHook, TerrainHook, TrailHook,
VectorTileSourceHook, VideoSourceHook, ZoomRangeHook.
DrawHooks, from maplibrex/draw, adds DrawHook, the hook of <.draw>,
which is not in MapHooks: only an application that draws imports it, once
it has installed Terra Draw (step 2), and adds it next to MapHooks:
import { MapHooks } from "maplibrex"
import { DrawHooks } from "maplibrex/draw"
const liveSocket = new LiveSocket("/live", Socket, {
longPollFallbackMs: 2500,
params: {_csrf_token: csrfToken},
hooks: {...colocatedHooks, ...MapHooks, ...DrawHooks},
})
A <.draw> rendered without it draws nothing, and the browser console says
which lines to add.
If your application has a hook of its own under one of these names, a
MapHook that wrapped a map before you adopted MaplibreX say, the two
collide: hooks holds one hook per name, the spread that comes last wins,
and nothing is logged. With ...MapHooks last, as above, the components
keep working and your hook of that name no longer runs: rename it, and the
phx-hook attributes that name it. With your hooks last, the component
that names that hook mounts yours instead: for MapHook, no map appears,
and the components on that map wait for it.
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:
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:
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.
Terra Draw needs no flag: the bundle does not import it, and
maplibrex/draw, which does, is imported only by an application that
installed it.
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"}:
import { MapHooks } from "../../../maplibrex/priv/static/assets/js/maplibrex.js"
// Only to draw:
import { DrawHooks } from "../../../maplibrex/priv/static/assets/js/draw.js"
Keep the assets/node_modules entry in NODE_PATH: the bundle still imports
maplibre-gl from there, and draw.js imports Terra Draw 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:
"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:
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:
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:
@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
defmodule MyAppWeb.MapLive do
use MyAppWeb, :live_view
import MaplibreX.Components
# ...
end
A component pushes an event to the LiveView it is rendered in (also from
inside a LiveComponent) only when its events attribute names it, so a
plain <.map> pushes none. Give each component the events you handle, and
write a handle_event/3 clause for each (see Events):
<.map id="map" center={@center} zoom={@zoom} class="h-96 w-full" events={["map:moved"]} />
def handle_event("map:moved", %{"center" => center, "zoom" => zoom}, socket) do
{:noreply, assign(socket, center: center, zoom: zoom)}
end
A LiveView with no clause that matches an event it receives crashes on it:
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. events keeps that from happening: list only the events
you have clauses for.
Configuration
Optional defaults, in config/config.exs:
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, and trail, the line of where a marker, or
each point of a layer, has just been
Sources — vector_tile_source, raster_tile_source, raster_dem_source,
image_source, video_source
Images — image, an icon of your own (or a pulsing dot) for symbol layers
to draw
Controls — navigation_control, scale_control, fullscreen_control,
geolocate_control, attribution_control, terrain_control, control,
control_button, control_group, zoom_range
3D & terrain — terrain, sky
Drawing — draw
Advanced — deckgl_layer, custom_layer, flow_layer
Every component is documented with attributes, events and examples on HexDocs.
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, trail, custom_layer, flow_layer, image, terrain
and sky 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. A marker given transition moves to a new position over that
many milliseconds instead of jumping there, as a vehicle of a live fleet does
between two reports, and a <.map> given follow, a marker's id, keeps that
marker at its centre as it moves, until the user drags the map; given a tuple of
a geojson_layer's id and a feature's id, {"fleet", 21}, it keeps that point
of the layer at its centre the same way. A geojson_layer whose features have ids gives the map
only the features that changed in new data, and takes the changed features
alone from the server with layer:update_data; given transition, its point
features move to their new positions over that time too, a heading property
turning with them. A geojson_layer, and the circle_layer, line_layer,
fill_layer, symbol_layer, fill_extrusion_layer and heatmap_layer over
the source they name, also set the feature state their feature_state
attribute and their pushes give, such as a selected or alerted feature, and
set it again after a map style change. A clustered geojson_layer opens a
cluster on a click with cluster_expand_on_click, and tells the LiveView
which points a cluster holds when it asks. A trail keeps, in the browser, the last positions of a
marker, or of each point of a geojson_layer, and draws them as a line that
grows behind it as it moves, bounded by a number of positions or an age and
broken where it jumps. All of these
also come back on a <.map> that is removed and rendered again under the same
id (behind :if, say). deckgl_layer too
can come before or after its map, follows its assigns and comes back on a map
rendered again under its id; several on one map draw in the order of the
template. draw lets the user draw and edit shapes, which reach your
LiveView as GeoJSON, and shows and lets the user edit the ones your LiveView
gives it in features, such as stored geofences, under your own ids and
in your own colours; its hook comes from maplibrex/draw (see step 3). It too can come before or
after its map, and its shapes come back after a map style change and on a
map rendered again under its id.
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
The events a component is asked for (see below) arrive in your LiveView as
ordinary handle_event/3 calls. The map, markers, layers and drawings push these:
| 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}, with "sourceId", "status", "url" and "tile" when MapLibre gives them: where the error came from (see "Errors" in MaplibreX.Components.Map) |
map:follow_ended |
%{"mapId" => id, "markerId" => marker_id, "reason" => reason}, or for a feature of a layer %{"mapId" => id, "layerId" => layer_id, "featureId" => feature_id, "reason" => reason}: the map stopped following the marker or the feature follow names, because the user took the map ("user") or a camera command moved its centre ("command") |
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; "features" and "lngLat" instead of "feature" for fill_extrusion_layer); a click on a cluster of a clustered geojson_layer adds "cluster_id" and "point_count" |
layer:cluster_leaves_loaded |
%{"layer_id" => id, "cluster_id" => cluster_id, "features" => features, "limit" => limit, "offset" => offset}, with "ref" when the request had one, or "error" in place of "features": the points of a cluster a LiveView asked a geojson_layer for, pushed whatever events says |
draw:created / draw:updated / draw:deleted |
%{"draw_id" => id, "feature" => feature}: the shape drawn, edited or deleted, under the id features gave it (a UUID for a shape the user drew), a circle with its "center" and "radius" in metres |
map:moved is debounced by 150 ms so continuous panning does not flood the
socket.
A component pushes only the events its events attribute names, and none
without it (#45),
so the others cost no round trip and need no handle_event/3 clause:
<.map id="map" events={["map:moved", "map:clicked"]} /> pushes those two.
events={:all} pushes every event the component emits; a LiveView that uses
it needs a clause for each of them. Each component's docs list the events it
can push, and a name it does not push raises an ArgumentError when it
renders. A new events value applies from the next event on, without
recreating the map or the component. A layer shows the pointer cursor over
its features while it asks for one of its layer:feature_* events.
A layer whose features react in the browser alone (hover and selection done
with feature state, say) needs no event for its cursor: give it cursor,
and it shows that cursor over its features and pushes nothing
(#114):
<.geojson_layer id="parcels" map_id="map" type="fill" data={@parcels} cursor="pointer" />
cursor takes any CSS cursor, such as "crosshair", and on a layer that
also asks for a feature event it shows instead of the pointer. The layers
whose features MaplibreX reports take it: circle_layer, line_layer,
fill_layer, symbol_layer, fill_extrusion_layer and geojson_layer.
The same layers light the feature under the pointer themselves with
hover, which gives it the feature state hover while the pointer is on
it, in the browser, with nothing pushed
(#171):
<.geojson_layer
id="parcels"
map_id="map"
type="fill"
data={@parcels}
promote_id="parcel_id"
cursor="pointer"
hover
paint={%{"fill-opacity" => ["case", ["boolean", ["feature-state", "hover"], false], 0.8, 0.4]}}
/>
A DOM event tells the page which feature is under the pointer, so a row of
a table beside the map can light up with it, and hover/2 and
unhover/1 light a feature from outside the map, a row say: see "Hover"
in MaplibreX.Components.GeoJSONLayer and in the JavaScript API guide.
A thin line is a thin target. With hit_width, a number of pixels, the
same layers answer the pointer within that many pixels of what they draw:
their events, cursor and hover, and a tap on a phone
(#173):
<.line_layer id="routes" map_id="map" source_id="routes" events={["layer:feature_clicked"]} hit_width={12} />
For a polygon drawn by its outline, a fill_layer with fill-opacity 0
over the same source answers in the whole area: see "Hollow polygons" in
MaplibreX.Components.LineLayer.
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:
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:
# 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.
A <.geojson_layer> takes layer:update_data, with only the features that
changed, so that a live fleet sends a vehicle's new position rather than the
whole collection:
push_event(socket, "layer:update_data", %{layer_id: "fleet", update: [vehicle_feature]})
See "Updating part of the data" in MaplibreX.Components.GeoJSONLayer.
A <.geojson_layer> also sets feature state, which its paint properties
read with ["feature-state", "<key>"], without sending any data: give it
a map of feature id => state in feature_state, and it sets in the
browser only what changed; or push only what changed with
layer:set_feature_state, and remove it with layer:remove_feature_state
(#170):
push_event(socket, "layer:set_feature_state", %{layer_id: "fleet", states: %{"V-21" => %{alert: false}}})
The state the layer sets comes back after a map style change. See "Feature
state" in MaplibreX.Components.GeoJSONLayer. The layers over a source they
name, such as a <.fill_layer> over a vector tile source for a choropleth
with a selected region, take the same attribute and pushes, and set the
state on their source_id and source_layer: see "Feature state" in
MaplibreX.Components.FillLayer.
A clustered <.geojson_layer> tells the LiveView which points a cluster
holds: push layer:cluster_leaves with the cluster_id a click on the
cluster gave, and the layer answers with the event
layer:cluster_leaves_loaded, whatever its events say
(#178):
def handle_event("layer:feature_clicked", %{"cluster_id" => id}, socket) do
{:noreply, push_event(socket, "layer:cluster_leaves", %{layer_id: "places", cluster_id: id, limit: 50})}
end
cluster_expand_on_click opens a cluster on a click, in the browser. See
"Clusters" in MaplibreX.Components.GeoJSONLayer.
Tracking a fleet
The Tracking a fleet guide puts the pieces of a
live fleet map together, from the GPS report to the vehicle on the screen:
positions batched on the server and sent through Phoenix.PubSub, a
complete LiveView with markers and one with a layer fed by pushes, movement
between reports, following a vehicle and trails. It gives the numbers
measured for each way of sending positions, what to use at each size of
fleet, and what stays with the application, such as map matching and the
storage of positions.
JavaScript API
Your own JavaScript can work with the maps MaplibreX creates: listen to
MapLibre events, set feature state, drive a map from a client-side store.
The JavaScript API guide documents what the
maplibrex package exports for that (MapManager, useMap, requireMap
and followMap), the ids of the sources and layers each component keeps on
the map, and what your code may change of them. maplibrex/map-manager
exports the same four without maplibre-gl, so that code using them can be
tested in Node.
PMTiles
A source can read its tiles from a PMTiles
archive, one static file, with no tile server: register the protocol of
the pmtiles package in app.js, and give <.vector_tile_source> or
<.raster_tile_source> a pmtiles:// URL. The PMTiles
guide shows how, with an archive served from priv/static, and says what
was tested.
Demo
A Phoenix application with example pages built on MaplibreX: maplibrex_demo
Development
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):
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. Bug reports and pull requests are welcome.
License
MIT — see LICENSE.