Maps are one integration among others: the core entry knows nothing about them. The optional entry
live_slice/maplibre binds a store to a MapLibre GL JS map that the app passes in.
It imports nothing (no runtime dependencies, no maplibre-gl import) and uses only the map's public API:
on, off, getSource, getLayer, setFeatureState, removeFeatureState, queryRenderedFeatures,
listImages, getCanvas, the camera getters and jumpTo.
import { bindMap } from "live_slice/maplibre";
const unbind = bindMap(store, map, {
viewport: {},
selection: { sources: ["places"], layers: ["places-layer"], clearOnMiss: true, cursor: "pointer" },
hover: { sources: ["places"], layers: ["places-layer"] },
});
// Later, when the hook goes: removes every listener and subscription, unmarks the features and
// puts the cursor back.
unbind();Each option is optional; bindMap binds only what it is given.
viewportwrites the map's camera to a store key when bound and once permoveend.key("viewport"),events(["moveend"]).read(map)returns the value to store; by default (exported asreadViewport){center: [lng, lat], zoom, bearing, pitch, bounds: [west, south, east, north]}. It must return plain JSON: the bridge compares mirrored values by content, so a copy of the same viewport is never pushed, and the binding writes nothing when the value did not change.initial: falseskips the write when bound (moveenddoes not fire for the initial camera).apply: truemoves the map withjumpTo(center,zoom,bearing,pitch) when the key is changed from outside;apply: (map, value) => ...moves it any other way (easeTo,fitBounds). A value the key already holds when bound (a deep link, a server patch, the camera of the map bound before) moves the map too, before its first report; without one the map stays where it is. A value equal to the map's own last report is never applied back, so there is no feedback loop.
selectionandhoverkeep a feature id in a store key ("selectedId","hoveredId") and mark that feature with feature state ({selected: true},{hover: true};statechanges the name) in every listed source, unmarking the previous one.sourcesare source ids or{source, sourceLayer}(vector sources need their source layer). Withlayers, a click (selection) or the pointer (hover) over a feature of those layers writes its id: a click on no feature keeps the selection unlessclearOnMissis true, and the hover is cleared over no feature and when the pointer leaves the map (mouseout; MapLibre'smouseleaveonly exists per layer). The hover is written only when the id changes. Withoutlayers, the store drives the map only. Paint the layers with thefeature-stateexpression, for example["case", ["boolean", ["feature-state", "selected"], false], 9, 4]. Features need stable ids, numbers or strings: a top-levelidin GeoJSON, or the source'spromoteId.cursor(a CSS cursor, such as"pointer"; it needslayers) shows that cursor on the map's canvas (map.getCanvas().style.cursor) while the pointer is over a feature with an id of those layers, and puts back the one it had when the pointer is over none or leaves the map, and onunbind, unless someone else changed it meanwhile. Give it toselectionto show that a click selects. Aselectionwithout it does not watch the pointer at all; withhoverover the same layers, the two share one query per pointer move.
onStyleChange(map)is called after a style change (a new basemap), diffed or rebuilt, dropped a source that was on the map, once the new style accepts sources and layers again. Every style change drops the sources and layers the app added itself, so add them back there. The sources watched areownSources(source ids), or else theselectionandhoversources.ownSourcesmay also be a function(map) => ids, asked at each style event for the sources the app keeps on the map now: see Own sources and managed ones for when that matters.
unbind(mapRemoved) is idempotent and harmless on a map that was removed already; with true it does not
touch the map's feature state or its cursor. The store's state stays as it is, so a map bound later (a map
created again) shows the same selection.
Re-applying feature state
Feature state belongs to a source object. New data (setData) keeps it; a source added again starts without
it. That happens to a source more often than one might think: a source the app added goes with every style
change, diffed or rebuilt, and a source a component library manages is added again on every style change
too, when the component replaces its source, and on a new map. maplibrex's
JavaScript API guide
("Feature state") spells this out and gives the recipe the binding follows: remember the source object the
marks were set on, and set them again on each new one. The binding checks on sourcedata of a listed source
and on styledata and style.load, so data updates and events about the same source set nothing again.
It is built for the cases a map meets in practice:
- The map can be bound before its style or its sources exist. A mark for a source that does not exist yet
waits for the source; a feature state call while the style is loading (MapLibre throws "Style is not
done loading.") is retried on the next event. Pointer queries skip
layersthat do not exist yet, since MapLibre reports a query naming a missing layer as an error. - Style events can fire synchronously from inside a feature state call or a style change (a render that a
library forces before diffing a style): the binding ignores events that arrive while it is applying
marks or running
onStyleChange, and it never listens torender. - Only feature state is touched: never paint, layout, filters or data.
Own sources and managed ones
A source the app adds itself with map.addSource belongs to the app: every style change drops it with its
layers (a diff keeps only what the new style has, a rebuild keeps nothing), and only the app can add them
back, in onStyleChange:
const addPlaces = (map) => {
if (!map.getSource("places")) map.addSource("places", { type: "geojson", data: placesGeoJSON });
if (!map.getLayer("places-layer")) {
map.addLayer({
id: "places-layer",
type: "circle",
source: "places",
paint: { "circle-radius": ["case", ["boolean", ["feature-state", "selected"], false], 9, 4] },
});
}
};
addPlaces(map);
bindMap(store, map, {
selection: { sources: ["places"], layers: ["places-layer"] },
// The selection is marked again once the source is back.
onStyleChange: addPlaces,
});MapLibre has no event that tells a style change on every path: maplibre-gl 6 fires style.load after a
diffed style change too, but maplibre-gl 5 does not, and a diff fires the same sourcedata and styledata
as the app's own map.removeSource. So the binding takes a watched source that was on the map and is gone at
a style event for a style change. An app that removes one of its sources on purpose (a dataset turned off)
says so with an ownSources function, which returns the sources it keeps on the map now; a source it no
longer returns is not watched, and has to be seen on the map again before its absence counts:
bindMap(store, map, {
selection: { sources: ["places"], layers: ["places-layer"] },
ownSources: () => (store.getState().showPlaces ? ["places"] : []),
onStyleChange: (map) => store.getState().showPlaces && addPlaces(map),
});The demo's / page adds its own source and layers the same way; it never changes its basemap, so it passes
no onStyleChange. A source that a component library manages (for example maplibrex's
<.geojson_layer>) comes back by itself after a style change, as a new source; the binding marks it again.
Either way, the binding needs no other knowledge of who owns a source. On a new map (a map element rendered
again), bind again: maplibrex's followMap below does that.
maplibrex
maplibrex renders MapLibre maps as LiveView components (<.map>,
<.geojson_layer>, ...). Tested with maplibrex 0.4.0 from Hex, maplibre-gl 6.18.0, Phoenix LiveView 1.2.15
and Phoenix 1.8.17 (the demo's /maplibrex page). live_slice never imports maplibrex: the app reaches
maplibrex's maps with maplibrex's own followMap and hands each one to bindMap. maplibrex's public
JavaScript contract is its JavaScript API guide:
what it exports, which source and layer ids each component owns, and when feature state is lost; the binding
and the rules below follow it.
<%!-- No events: the LiveView handles none of the components' events. --%>
<.map
id="places-map"
style="https://demotiles.maplibre.org/style.json"
center={[3.0, 44.0]}
zoom={4}
class="h-full w-full"
/>
<.geojson_layer id="places-layer" map_id="places-map" type="circle" data={@data} paint={@paint} />import { ensureStore, removeStore } from "live_slice";
import { bindMap } from "live_slice/maplibre";
import { followMap } from "maplibrex";
export const PlacesMap = {
mounted() {
const store = ensureStore("map:places-map", {
state: { viewport: null, selectedId: null, hoveredId: null },
});
const features = { sources: ["places-layer-source"], layers: ["places-layer"] };
this.stopFollowing = followMap("places-map", (map) =>
bindMap(store, map, {
viewport: {},
selection: { ...features, clearOnMiss: true, cursor: "pointer" },
hover: features,
}),
);
},
destroyed() {
this.stopFollowing();
removeStore("map:places-map");
},
};This is the demo's PlacesMap hook (demo/assets/js/places_hooks.js, which takes followMap as an argument
so that its tests can pass a fake). followMap(mapId, attach), exported by maplibrex from 0.4.0, calls
attach(map) as soon as maplibrex registers a map under mapId (at once if one is). When that map is removed
it calls what attach returned with true (the map is gone, listeners and all) and attaches to the map
registered in its place, or to the next one: maplibrex creates a new map when the <.map> element is rendered
again. The function it returns stops following and calls the cleanup with false. bindMap returns a
cleanup that takes that mapRemoved flag, so it is returned from attach as is.
Rules that keep the two libraries out of each other's way:
- Reach maps only through
followMapandMapManager(whenReady,whenNextRegistered,get,isRegistered); neverregisterorunregisterthem. maplibrex registers a map right after creating it, before itsloadevent, soattachmay get a map whose style and sources do not exist yet;bindMapcopes with that. From 0.4.0,MapManager.get(mapId)returnsundefinedfor a missing map without a warning;requireMap(mapId)warns and throws. - Feature state on a managed source, yes: it is how hover and selection should be drawn. Paint, layout,
filters and data of a managed layer or source, no: drive those through assigns (a value set from
JavaScript lasts only until the next render that changes it, or the next style change). maplibrex names
the source of
<.geojson_layer id="places-layer"> places-layer-source(<id>-source); the guide's table lists the ids of every component. - Feature state on a component's source is lost on every style change, diffed or rebuilt, when
<.geojson_layer>replaces its source (turningclusteroff, a newcluster_properties,generate_idorpromote_id) and on a map rendered again; newdatakeeps it.bindMapmarks each new source again; sources and layers you add yourself needonStyleChange. - Features need stable ids: a top-level
idon each GeoJSON feature (the demo gives each place a numeric one), or, from 0.4.0,promote_idon<.geojson_layer>, which takes each feature's id from a property and passes it to the source aspromoteId: withpromote_id="uuid", the store'sselectedIdholds a feature'suuid, a string or a number. Avoidgenerate_id: it numbers features by position, which changes with the data, and it excludespromote_id. 0.4.0 also takes a URL asdata. - Do not render the mirrored viewport back into
<.map>: keep itscenterandzoomthe ones it opened with, or every report would move the map again. - Events are opt-in from 0.4.0: a component pushes only the events its
eventsattribute names, and none without it. When the store carries the interaction, give the components noevents, or only those your LiveView handles;bindMaplistens on the MapLibre map itself, so selection and hover send nothing over the websocket. The demo's LiveView handles none, so its<.map>and<.geojson_layer>have noevents. (On 0.3.x, which pushes every event without aneventslist, passevents={[]}.) - From 0.4.0 a layer that asks for no
layer:feature_*event shows no pointer cursor over its features. GivebindMap'sselectionacursor: "pointer"rather than asking forlayer:feature_clickedfor the cursor's sake, which would push every click on a feature to the LiveView. MapHooksadds 33 keys to the LiveSocket'shooks(MapHook,MarkerHook,GeoJSONLayerHook, ...; maplibrex's README lists them). A hook of your own under one of those names silently replaces maplibrex's, or is replaced, whichever spread comes last: give your hooks other names (the demo's own map hook isFeatureMap).- Setup, from maplibrex's README: install
maplibre-glinassets/within maplibrex's peer range (>=5.0.0 <7.0.0for 0.4.0). The bundle indeps/maplibreximportsmaplibre-glfromassets/node_modules, so addPath.expand("../assets/node_modules", __DIR__)to theNODE_PATHof the esbuild profile: the app and maplibrex then share one copy (the demo'sapp.jsbundles a singlemaplibre-glmodule). Add--external:@deck.gl/*to itsargsunless deck.gl is installed; with<.deckgl_layer>, 0.4.0 needs deck.gl 9.4 with@deck.gl/maplibrein place of@deck.gl/mapbox. Import../../deps/maplibrex/assets/css/maplibrex.cssinapp.css. With maplibre-gl 6, copy its worker next toapp.jsand callsetWorkerUrl(the demo does it with a second esbuild profile; maplibrex 0.4.0 also hasmix maplibrex.copy_worker). - Upgrading from maplibrex 0.3.0: its changelog's
Upgrading from 0.3.0 lists every
change. For a map bound with
live_slice: follow it with maplibrex'sfollowMap(...)as above, drop theevents={[]}that silenced 0.3.0, addcursor: "pointer"to the selection, and read the data of<.geojson_layer>fromdata-geojsonrather thandata-configin tests that decode the rendered markup.