MaplibreX.Components.Map (MaplibreX v0.4.0)

Copy Markdown View Source

Map component for rendering MapLibre GL JS maps in Phoenix LiveView.

Examples

Basic map:

<.map
  id="my-map"
  center={[-74.5, 40]}
  zoom={9}
  style="https://demotiles.maplibre.org/style.json"
  class="h-96"
/>

Map with all options:

<.map
  id="detailed-map"
  center={[-74.5, 40]}
  zoom={9}
  style="https://demotiles.maplibre.org/style.json"
  min_zoom={5}
  max_zoom={15}
  bearing={0}
  pitch={0}
  interactive={true}
  attribution_control={true}
  class="h-screen w-full"
/>

Map with event handling. The map pushes only the events its events attribute names, so the LiveView needs a clause for those only:

def render(assigns) do
  ~H"""
  <.map
    id="interactive-map"
    center={@center}
    zoom={@zoom}
    style={@map_style}
    events={["map:clicked", "map:moved"]}
    class="h-96"
  />
  """
end

def handle_event("map:clicked", %{"lngLat" => lngLat}, socket) do
  IO.inspect(lngLat, label: "Map clicked at")
  {:noreply, socket}
end

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

events={:all} pushes every event the map emits; a LiveView that uses it needs a clause for each of them.

Nesting components

Components can be nested in the map. They behave exactly as they do when rendered right after it:

<.map id="my-map" center={@center} zoom={@zoom} class="h-96">
  <.vector_tile_source id="places" map_id="my-map" url={@tiles_url} />
  <.circle_layer
    :if={@show_places}
    id="places-points"
    map_id="my-map"
    source_id="places"
    source_layer="place"
    paint={@places_paint}
  />
  <.marker :for={pin <- @pins} id={pin.id} map_id="my-map" lng_lat={pin.coords} />
</.map>

Every nested component still names its map with map_id.

The slot is rendered right after the map element, as its sibling, not inside it. The map element is phx-update="ignore", because MapLibre owns its DOM, so LiveView never patches anything inside it; next to it, nested components follow their assigns and mount and unmount with :if and :for like any other component.

Visible slot content is therefore laid out after the map, not on top of it, and is not part of the map in fullscreen. To show your own content on the map, use the control, control_button and control_group components: MapLibre places them in its control corners, inside the map. Or position it yourself in a wrapper of your own (give the wrapper's id to fullscreen_control as container_id to take it into fullscreen):

<div class="relative">
  <.map id="my-map" class="h-96" />
  <div class="absolute bottom-8 left-2 rounded bg-white p-2 shadow">Legend</div>
</div>

Opening flight

A map given fly opens far out and, once its first render is complete (MapLibre's first idle event), flies to its camera, the opening known from Google Earth. It is off by default:

<.map id="map" center={[-9.14, 38.72]} zoom={11} fly />

fly is true, or a map of these options, each optional, with atom or string keys (nil counts as not given, an unknown key raises):

  • from - the camera the flight starts from: center ([longitude, latitude]), zoom, bearing and pitch. Any of them not given takes its default: [80, -20], a point over the Indian Ocean from which Africa and South Asia are in view, zoom 0.8, bearing and pitch 0
  • duration - how long the flight takes, in milliseconds. Defaults to 2800 when speed is not given
  • speed - MapLibre's flight speed instead, 1.2 unless given: the flight then takes as long as its length needs at that speed. MapLibre ignores the speed when a duration is given, so duration and speed together raise an ArgumentError
  • curve - MapLibre's flight curve, 1.42 unless given: how far the map zooms out on the way. Goes with either duration or speed

For example:

<.map
  id="map"
  center={[-9.14, 38.72]}
  zoom={11}
  fly={%{from: %{center: [80, -20], zoom: 0.8}, duration: 2800}}
/>

The flight lands where the map would have opened without fly: on its center, zoom, bearing and pitch, or the configured default_center and default_zoom when it has no center or zoom, or on its bounds, fitted as the map opens on them. The starting camera is kept within min_zoom, max_zoom, min_pitch, max_pitch and max_bounds. A map that has no camera of its own and none configured (default_center: nil and default_zoom: nil) opens at the camera of its style and does not fly. The flight pushes no event of its own: like any move, it ends with one map:moved where the map lands.

The flight runs once, when the map mounts, and gives way to everything else:

  • When the user's system asks for reduced motion (prefers-reduced-motion: reduce), the map opens at its camera and does not fly. The opening flight is never essential: the camera commands, fly_to/4 and fit_bounds/3, give way to reduced motion too, unless the application marks them essential: true.
  • The user moving the map, or a camera command (fly_to/4, jump_to/4, fit_bounds/3, zoom_in/1, zoom_out/1, reset_north/1, or one pushed from the server), stops the flight, or keeps it from starting, and the map stays where they put it. It does not resume.
  • A center, zoom, bearing, pitch or bounds the LiveView changes before or during the flight wins: the flight is abandoned, and the map goes at once where it would be without fly, with the new value. A re-render that changes another attribute, or that renders back the camera the map reported in map:moved, leaves the flight alone, and so does a style change. A value that differs from the one before only by float noise, or by the rounding of map:moved, is not a change: a map replaced by one with the same id and fly keeps its flight when the LiveView renders it the camera the old map reported.
  • fly is read when the map mounts only: changing it, adding it or removing it later does nothing.

The flight looks best on a globe. Give the map projection="globe" (see "Projection"): the globe is in place before the flight starts, with any style:

<.map id="map" center={[-9.14, 38.72]} zoom={11} projection="globe" fly />

With curtain (see "Loading curtain"), the flight starts once the curtain is gone, so that the visitor sees it from its start.

Projection

Without projection, the style decides the projection: the one it declares in its own projection, or mercator, the flat map. With it, the map is drawn in that projection, whatever its style declares (MapLibre GL JS 5 and later):

<.map id="map" center={[-9.14, 38.72]} zoom={2} projection="globe" />

projection is the name of one of MapLibre's projections, as a string or an atom: "mercator"; "globe", which draws the Earth as a sphere when zoomed out and turns into mercator as the map zooms in, between zoom 11 and 12; "vertical-perspective", the sphere at every zoom. Names are not checked here, so that a projection a later MapLibre adds works as well: MapLibre logs a warning for a name it does not know and draws mercator. For anything beyond a name, projection is a map, passed to MapLibre as its projection specification, such as a globe that turns flat at other zoom levels:

projection={%{type: ["interpolate", ["linear"], ["zoom"], 4, "vertical-perspective", 6, "mercator"]}}

The map sets its projection once its style has loaded, and again on every new style, whether it comes from a new style, set_style/2 or a pushed map:set_style: each style brings its own projection, or none. A new projection after mount applies at once, or once the style that is loading has loaded. Without projection again, the map goes back to the projection its current style declares, or mercator.

On a globe the camera follows the assigns as on a flat map: a new center keeps the map's zoom, and a new min_zoom or max_zoom zooms a map outside the new range into it at once. MapLibre's globe alone changes the zoom with the latitude of a new centre, to keep the planet's apparent size (a centre moved from Madrid to Nairobi at zoom 11 would land at 11.39), and keeps a zoom past a new limit until the map next moves. The pushed map:fly_to and map:jump_to events reach MapLibre as they are: one without a zoom gets the zoom MapLibre's globe works out.

3D terrain is drawn on a globe too, with one limit of MapLibre 5 and 6: while the globe is drawn as a sphere, MapLibre logs once "terrain is not fully supported on vertical perspective projection" and, when the map has moved, does not bring the centre of the map onto the terrain's surface, as it does on a flat map.

Loading curtain

While a map draws for the first time, its tiles arrive and are redrawn at one level of detail after another. A map given curtain hides that: an opaque cover with a loader stands over the map until its first render is complete (MapLibre's first idle event), then fades out. It is off by default:

<.map id="map" center={[-9.14, 38.72]} zoom={11} curtain />

The curtain is rendered inside the map element, so it is there from the first paint, before any JavaScript runs; the map element keeps its id, its hook and its class, and MapLibre draws the map behind the curtain. While the curtain covers the map, the map element has aria-busy="true", and the curtain is a role="status" with a text for assistive technology, "Loading map". Once the map has rendered, aria-busy goes, the curtain at once stops taking focus and pointer events (it becomes inert) and fades out, and it is then hidden (hidden).

curtain is true, or a map of these options, each optional, with atom or string keys (nil counts as not given, an unknown key raises):

  • timeout - the longest the curtain covers the map, in milliseconds, 8000 unless given. A map whose first render has not completed by then (a tile server that does not answer, a network that is gone) is shown as it is
  • label - the status text for assistive technology, "Loading map" unless given

For example:

<.map id="map" curtain={%{timeout: 5000, label: "Cargando el mapa"}} />

The curtain also lifts at once when the map's style cannot be loaded, or MapLibre cannot create the map: such a map does not render, and the curtain would only hide that. An error about a tile or a source leaves it in place: the map still renders.

Your own loader

The loader slot replaces the built-in loader, a turning ring, with markup of your own. The label is still there for assistive technology, so mark your loader aria-hidden="true" unless it says something the label does not:

<.map id="map" curtain>
  <:loader>
    <img src="/images/logo.svg" alt="" aria-hidden="true" class="size-12 motion-safe:animate-pulse" />
  </:loader>
</.map>

Without curtain, the slot is ignored. Components for the map still go in the default slot, which is rendered after the map element as always.

Styles

The curtain's styles are in the library's stylesheet, maplibrex.css (see the README). Restyle the curtain with these CSS custom properties, set on :root, on a wrapper or on the map element; the stylesheet never sets them, so no !important is needed:

  • --maplibrex-curtain-background - the curtain's background, Canvas unless set: the background of a page in the color scheme the page uses (its CSS color-scheme), white on a light page and near black on a dark one, which follows a theme toggle that sets color-scheme. A page that is dark without declaring color-scheme gets a white curtain: set this property for it
  • --maplibrex-loader-color - the colour of the built-in loader, #3498db unless set
  • --maplibrex-curtain-fade - how long the curtain fades out, 300ms unless set; 0s for no fade

For example, for a dark basemap on a light page:

#map {
  --maplibrex-curtain-background: #050810;
  --maplibrex-loader-color: #f8fafc;
}

With prefers-reduced-motion: reduce, the curtain does not fade and the built-in loader does not turn: the curtain covers the map, then disappears. For other changes, the curtain is .maplibrex-curtain, the built-in loader .maplibrex-loader and the label .maplibrex-curtain-label; while it fades out, the curtain is .maplibrex-curtain[inert], and once gone .maplibrex-curtain[hidden]. The stylesheet stacks it above MapLibre's controls, which it covers too.

A page without the library's stylesheet has no cover: the curtain is then an unstyled element at the top of the map element, under MapLibre's canvas, and its label shows as plain text until the map draws over it. It is hidden once the map has rendered, as always: hidden needs no stylesheet.

With fly and projection

With fly, the flight starts once the curtain is gone, so that the visitor sees it from its start. When the timeout lifts the curtain before the map's first render, the flight still waits for that render, as it does without a curtain. With projection, the map is already drawn in its projection when the curtain lifts.

Once, at mount

The curtain is for the map's first render. curtain is read when the map mounts only, like fly: adding, changing or removing it later does nothing, and the curtain never comes back, on a new style or for anything else. A map removed before its curtain is gone leaves no timer or listener behind. The curtain pushes no event of its own: map:loaded and the others are pushed when they would be without it.

Summary

Functions

Creates a JS command to fit the map to specific bounds.

Creates a JS command to fly the map to a specific location.

Creates a JS command to jump the map to a specific location (no animation).

Renders a MapLibre GL JS map component.

Creates a JS command to reset the map's bearing to north.

Creates a JS command to set the map style.

Creates a JS command to zoom in.

Creates a JS command to zoom out.

Types

bounds()

@type bounds() :: {center(), center()} | [center()]

center()

@type center() :: {float(), float()} | [float()]

Functions

fit_bounds(map_id, bounds, opts \\ [])

@spec fit_bounds(String.t(), bounds(), keyword()) :: Phoenix.LiveView.JS.t()

Creates a JS command to fit the map to specific bounds.

Examples

<button phx-click={MaplibreX.Components.Map.fit_bounds("my-map", [[-74, 40], [-73, 41]])}>
  Fit to bounds
</button>

With padding and max zoom:

fit_bounds("my-map", bounds, padding: 50, max_zoom: 15)

Options

  • :padding - pixels to leave around the bounds. Defaults to 50
  • :max_zoom - the highest zoom the fit may reach
  • :duration - how long the animation takes, in milliseconds. Defaults to 1000
  • :essential - true to animate also for a visitor whose system asks for reduced motion, as for fly_to/4. Without it, MapLibre fits such a visitor's map at once

fly_to(map_id, center, zoom, opts \\ [])

@spec fly_to(String.t(), center(), integer(), keyword()) :: Phoenix.LiveView.JS.t()

Creates a JS command to fly the map to a specific location.

Options

  • :duration - how long the flight takes, in milliseconds. Defaults to 1000
  • :bearing, :pitch - the bearing and pitch to fly to; without them the map keeps its own
  • :essential - true to fly also for a visitor whose system asks for reduced motion (prefers-reduced-motion: reduce). Without it, MapLibre moves such a visitor's map there at once, with no animation. Give it only when the animation itself is what the visitor needs

Examples

<button phx-click={MaplibreX.Components.Map.fly_to("my-map", [-74.5, 40], 12)}>
  Fly to NYC
</button>

With custom duration:

fly_to("my-map", [-74.5, 40], 12, duration: 3000)

jump_to(map_id, center, zoom, opts \\ [])

@spec jump_to(String.t(), center(), integer(), keyword()) :: Phoenix.LiveView.JS.t()

Creates a JS command to jump the map to a specific location (no animation).

Examples

<button phx-click={MaplibreX.Components.Map.jump_to("my-map", [-74.5, 40], 12)}>
  Jump to NYC
</button>

map(assigns)

Renders a MapLibre GL JS map component.

Attributes

After mount, the map follows a change to any of these attributes except id and class; each entry says what a change does. A value that did not change between two renders is never re-applied.

  • id (required) - Unique identifier for the map
  • center - Map center coordinates as [longitude, latitude]. Without it, or with nil, the map opens at the configured default_center, [0, 0] unless configured (see MaplibreX). A new value after mount moves the map there at once, at the zoom it has, also on a globe (see "Projection"); nil after mount leaves the map where it is. A centre the map itself has just reported in map:moved, rendered back by the LiveView, is not applied to it again
  • zoom - Zoom level, fractional values allowed. Without it, or with nil, the map opens at the configured default_zoom, 10 unless configured. After mount it behaves as center
  • style - Map style URL or style object. Without it, or with nil, the configured default_style. A new value after mount replaces the style; the layers, sources and terrain of the map's components come back on the new style, and changes to them that arrive while it loads (in the same update, say) are applied once it is in place
  • min_zoom - Minimum zoom level. Optional: without it, 0. A new value after mount applies at once and, when the map is outside the new range, zooms it into the range (which pushes map:moved); no longer giving it goes back to 0. MapLibre's own default is -2, at which a globe is about 30 pixels wide: give min_zoom={-2} for it
  • max_zoom - Maximum zoom level. Optional. After mount as min_zoom; no longer giving it restores MapLibre's default, 22
  • min_pitch - Minimum pitch in degrees. Optional. After mount as min_zoom, for the pitch; no longer giving it restores MapLibre's default, 0
  • max_pitch - Maximum pitch in degrees, up to 180 (MapLibre GL JS 5 and 6 refuse more). Optional. MapLibre caps pitch at 60 by default and silently clamps anything above it, so a 3D terrain view that wants a steeper camera has to raise this. After mount as min_pitch; no longer giving it restores the default, 60
  • bearing - Bearing (rotation). Defaults to 0. After mount it behaves as center
  • pitch - Pitch (tilt). Defaults to 0. After mount it behaves as center
  • bounds - Fit map to bounds [[west, south], [east, north]]. Optional. The map opens on them, whatever center and zoom say. New bounds after mount fit the map to them at once, with no animation and no padding, as when it opens, and win over a center or zoom changed in the same render; no longer giving them leaves the map where it is. For an animated fit, use fit_bounds/3
  • max_bounds - Maximum bounds the map can be panned to. Optional. A new value after mount applies at once; no longer giving it lifts the limit
  • interactive - Whether the user can move the map with the mouse, touch and the keyboard. Defaults to true. After mount, false turns off every one of MapLibre's interaction handlers and true turns them all on again, also on a map created with false. The JS and server-pushed commands move the map either way
  • attribution_control - Show MapLibre's attribution control, in the bottom-right corner. Defaults to true. After mount, false removes it and true adds it back. An <.attribution_control> (MaplibreX.Components.AttributionControl) on the map takes its place while it is there, so that the map shows one attribution control
  • fly - Open the map with a camera flight: it starts far out and flies to the map's camera once its first render is complete. true, or a map of from (the starting camera), duration or speed, and curve; see "Opening flight" in the module documentation. Off by default. Read when the map mounts only: a change after mount does nothing
  • projection - The map's projection: a name, "globe", "mercator", "vertical-perspective" or any other MapLibre knows, as a string or an atom, or a map, MapLibre's projection specification. Without it, or with nil or false, the style decides. Any other value raises an ArgumentError. The map keeps it through style changes. A new value after mount applies at once; no longer giving it goes back to the projection the style declares, or mercator. See "Projection" in the module documentation
  • curtain - Cover the map with a loader until its first render is complete. true, or a map of timeout (milliseconds, 8000 unless given) and label (the status text for assistive technology, "Loading map" unless given); see "Loading curtain" in the module documentation. Off by default. Read when the map mounts only: a change after mount does nothing
  • debug - Log MaplibreX's lifecycle messages ([MaplibreX] ...) in the browser console. Defaults to false. Debug output is for the whole page, every map and component on it: it is on while any map on the page has debug, or while window.__MAPLIBREX_DEBUG__ is true (see the README). A map without it does not turn off another's. A change after mount turns the output on or off at once. Warnings and errors are always logged
  • class - CSS classes for the map container. Read when the map mounts only: LiveView does not patch the attributes of the map element, which is phx-update="ignore", except its data-* ones. Put classes that change on a wrapper element
  • testid - Test ID for the map element (data-testid), patched like any data-* attribute
  • events - The events to push to the LiveView: a list of names, such as ["map:moved"], or :all for every one. Without it, the component pushes none, so the LiveView needs a handle_event/3 clause only for the events it lists. The names it takes are those under Events: map:moved, map:clicked, map:loaded, map:zoom_changed, map:error; any other raises an ArgumentError. A new value applies from the next event on

Events

The map emits the following events to LiveView:

  • map:moved - Fired when the map is moved (pan, zoom, rotate, pitch)
  • map:clicked - Fired when the map is clicked
  • map:loaded - Fired when the map finishes loading
  • map:zoom_changed - Fired when zoom level changes
  • map:error - Fired when an error occurs

Slots

  • inner_block - Optional content, typically other MaplibreX components for this map. It is rendered right after the map element, as its sibling, not inside the map container: see "Nesting components" in the module documentation
  • loader - Optional markup that replaces the built-in loader of the curtain; ignored without curtain. See "Loading curtain" in the module documentation

Attributes

  • id (:string) (required)
  • center (:list) - Defaults to nil.
  • zoom (:any) - number. Defaults to nil.
  • style (:any) - Defaults to nil.
  • min_zoom (:any) - number. Defaults to nil.
  • max_zoom (:any) - number. Defaults to nil.
  • min_pitch (:any) - number, degrees. Defaults to nil.
  • max_pitch (:any) - number, degrees, up to 180. Defaults to nil.
  • bearing (:any) - number, degrees. Defaults to 0.
  • pitch (:any) - number, degrees. Defaults to 0.
  • bounds (:list) - Defaults to nil.
  • max_bounds (:list) - Defaults to nil.
  • interactive (:boolean) - Defaults to true.
  • attribution_control (:boolean) - Defaults to true.
  • fly (:any) - true, or a map of :from, :duration or :speed, and :curve; read at mount only. Defaults to nil.
  • projection (:any) - a projection name, such as "globe" or :globe, or MapLibre's projection specification as a map. Defaults to nil.
  • curtain (:any) - true, or a map of :timeout and :label; read at mount only. Defaults to nil.
  • debug (:boolean) - log MaplibreX's lifecycle messages in the browser console, for the whole page. Defaults to false.
  • class (:string) - Defaults to "maplibrex-map".
  • testid (:string) - Defaults to nil.
  • events (:any) - a list of event names, or :all. Defaults to [].
  • Global attributes are accepted.

Slots

  • inner_block
  • loader - replaces the curtain's built-in loader; ignored without curtain.

reset_north(map_id)

@spec reset_north(String.t()) :: Phoenix.LiveView.JS.t()

Creates a JS command to reset the map's bearing to north.

set_style(map_id, style)

@spec set_style(String.t(), String.t() | map()) :: Phoenix.LiveView.JS.t()

Creates a JS command to set the map style.

Examples

<button phx-click={MaplibreX.Components.Map.set_style("my-map", "new-style-url")}>
  Change Style
</button>

zoom_in(map_id)

@spec zoom_in(String.t()) :: Phoenix.LiveView.JS.t()

Creates a JS command to zoom in.

zoom_out(map_id)

@spec zoom_out(String.t()) :: Phoenix.LiveView.JS.t()

Creates a JS command to zoom out.