HoloMap.Map (HoloMap v0.3.0)

Copy Markdown View Source

The map container. Everything else in HoloMap goes inside one.

<HoloMap.Map cid="explorer" style={@style_url} center={{-70.66, 19.45}} zoom={11}>
  <HoloMap.Source.GeoJSON id="parcels" data={@parcels} />
  <HoloMap.Layer.Fill id="parcels-fill" source="parcels" paint={%{fill_color: "#3b82f6"}} />
</HoloMap.Map>

The cid is the map's identity

cid is Hologram's component id, and HoloMap uses it as the map's name throughout: the DOM container is hm--<cid>, the browser registry is keyed by it, and it is the first argument to every HoloMap.API function. One identifier, no second id prop to keep in sync.

A cid is mandatory. Hologram only runs init/3, and therefore only allows actions, on stateful components, and the map needs an action to boot.

Sizing

A map with no height renders as a zero-pixel box, which is the single most common way to end up staring at a blank page. height defaults to "400px" for that reason. Pass class instead when the size comes from your own CSS, and set height={nil} to opt out of the inline style entirely.

The worker URL

MapLibre parses tiles in a Web Worker that it starts from maplibre-gl-worker.mjs, resolved relative to its own module URL. Hologram bundles MapLibre into a page bundle under /hologram/, so that resolution lands on a file which is not there. The symptom is a map that renders its background and never draws a single tile. MapLibre reports the failed worker through the map's error event, so on_error receives it, with the message "Worker failed to load. Check that the worker URL is correct.". A map without on_error leaves MapLibre to log it to the browser console.

HoloMap sets the URL explicitly to avoid that. The default assumes the application serves maplibre-gl-worker.mjs from /assets/; the Installation guide has the copy step, and worker_url overrides the path if the worker lives elsewhere.

The default URL carries the version of the MapLibre the page loaded as a v query parameter, /assets/maplibre-gl-worker.mjs?v=6.19.0 on 6.19.0, as MapLibre's own default has since 6.13.0. Upgrading maplibre-gl therefore changes the URL, and no cache can hand the new library the old worker. Plug.Static ignores the query and serves the file; a CDN in front of it has to keep the query in its cache key. A worker_url you set is used as it is, with nothing added: put a version or a content hash in it, or serve the file with headers that make browsers revalidate it, as Plug.Static's default ETag without a max-age does.

MapLibre keeps one worker URL per page, and the first map to boot sets it. A later map that asks for another one, its own worker_url or the default, runs on the page's worker, and the browser runtime logs a warning once for each other URL. Give every map on a page the same worker_url.

Declarative camera versus animated camera

center, zoom, bearing and pitch are state. Changing one jumps the camera there, and panning the map by hand does not write back into them: the props describe where the application thinks the camera should be, not where the user dragged it. Nothing re-renders while the user interacts, so there is no fight between the two.

When a camera move is an event rather than a value, such as flying to a search result, use HoloMap.API.fly_to/2 and leave the props alone.

The limits, min_zoom, max_zoom, min_pitch, max_pitch and max_bounds, are state as well. A change that leaves the camera outside the new limits makes MapLibre zoom, pitch or pan it back within them. Like a jump, that move is not reported: on_move_start, on_move_end, on_zoom_end and on_pitch_end do not fire for it. The camera props keep the values the application gave them, and the next move the user makes reports where the limits left the camera.

A limit set back to nil is lifted, and the camera is as free as on a map built without it: no bounds, a zoom from -2 to 22 and a pitch from 0 to 60, MapLibre's defaults. A camera prop set to nil is different: it leaves the camera where it is.

render_world_copies and pixel_ratio apply as they change too, and set back to nil they return to MapLibre's defaults: world copies drawn, and the device's pixel ratio. A new pixel_ratio resizes the canvas, which MapLibre reports as a move, and that move is not reported either.

Interaction

interactive, cooperative_gestures and the seven handler props, drag_rotate, drag_pan, scroll_zoom, double_click_zoom, box_zoom, keyboard and touch_zoom_rotate, apply as they change, so a "lock the map" toggle can be state:

<HoloMap.Map cid="explorer" style={@style} interactive={!@locked} />

interactive={false} turns off every handler MapLibre's interactive option covers: the seven above and MapLibre's touchPitch, which options reaches. It also takes away the grab cursor over the map and the canvas's place in the tab order, as MapLibre does for a map built that way. Set back to true or nil, it turns on again each of those handlers whose own prop is not false. A handler prop that changes while the map is not interactive applies once it is. cooperative_gestures stands apart, as in MapLibre: interactive leaves it as it is.

Global state

A style can read named values with MapLibre's global-state expression, and global_state sets them. One change to it restyles every layer that reads a name, in the browser, with no paint, layout or filter sent again:

<HoloMap.Map cid="explorer" style={@style} global_state={%{theme: @theme, min_population: @min}}>
  <HoloMap.Source.GeoJSON id="cities" data={@cities} />
  <HoloMap.Layer.Circle
    id="cities"
    source="cities"
    filter={[">=", ["get", "population"], ["global-state", "min_population"]]}
    paint={%{circle_color: ["match", ["global-state", "theme"], "dark", "#e5e7eb", "#111827"]}}
  />
</HoloMap.Map>

Each name is sent as written, an atom as its name: min_population stays min_population, since it is the application's own word and not a style property. A value is anything an expression can read, such as a number, a string, a boolean or a list.

The map is built with the global state, so the first render already draws with it. A change sets each name that changed with MapLibre's setGlobalStateProperty, and only those. A name taken out of the map, or set to nil, goes back to the default the style declares for it in its state, or to null when the style declares none. A name the style does not declare is set all the same, and global-state reads it.

The global state belongs to the style in MapLibre, and a new style starts from its own defaults. The browser runtime hands every new style the global state the map declares, whether MapLibre diffs it or builds it from scratch, so the values hold through a style change. A change made while a new style loads applies once it has loaded. A value set some other way, through HoloMap.Runtime.call/3, is not handed to a new style, which can set the name back to its default.

Setting the global state fires no map event. HoloMap.API.request/4 reads the state the map holds with "getGlobalState".

Projection

projection picks how the map is drawn: "mercator", "globe" or "vertical-perspective", or an expression that picks one, such as a globe for world views that turns flat when the map zooms in on a city:

<HoloMap.Map cid="world" style={@style} projection={@projection}
             on_projection_transition={:projection_changed}>
  <HoloMap.Control.Globe />
</HoloMap.Map>

projection={["step", ["zoom"], "vertical-perspective", 11, "mercator"]}

MapLibre has no projection option: the projection belongs to the style, and a style may declare its own. The prop wins over the style's. It is put in place once the first style has loaded, and as it changes, with MapLibre's setProjection, without a style reload. A style change keeps it: MapLibre is handed it in place of the new style's own when it diffs the new style, and it is put in place again once a style built from scratch has loaded. Set to nil, the projection goes back to the one the style declares, or to mercator for a style that declares none. A map without the prop draws with the style's projection, as MapLibre does.

MapLibre keeps the projection an expression made when it is asked for "globe" next, and goes on drawing as the expression does. The browser runtime puts mercator in place in between, unreported, so a prop that goes from an expression to "globe" draws a globe.

HoloMap.Control.Globe switches the projection as the user clicks it. The prop is put back only when its value changes, or the style does, as the camera props are: a render that leaves it as it was leaves the user's choice alone.

on_projection_transition reports each projection MapLibre puts in place: the one the map starts with, once its first style has loaded, a change to the prop, a click on HoloMap.Control.Globe, a style MapLibre diffs that changes the projection, and every style built from scratch, which puts one in place again. A style the prop replaces the projection of reports only the prop's. Its payload is the camera, as for the other map events, and projection, the projection's type as the prop takes it: a name, or the expression. An action that writes it back into the state the prop reads from changes nothing, and keeps that state in step with the control:

def action(:projection_changed, params, component) do
  put_state(component, :projection, params.projection)
end

A globe zooming in past an expression's switch, or past the zoom where MapLibre's own "globe" turns flat, is not a new projection, and is not reported.

HoloMap.Terrain and HoloMap.Sky stay through a change of projection. MapLibre draws terrain on a globe too, without the fog it gives terrain on a flat map, and logs "calculateFogMatrix is not supported on globe projection." once when it does. The sky's atmosphere_blend is the glow around a globe.

Glyphs and font faces

glyphs points the map's text at another glyph server, a URL with the {fontstack} and {range} tokens MapLibre fills in. font_faces names font files to draw text with, for scripts a glyph server cannot draw, such as Arabic or Khmer, whose letters change shape with the marks and letters next to them:

<HoloMap.Map
  cid="explorer"
  style={@style}
  glyphs="https://fonts.example.com/{fontstack}/{range}.pbf"
  font_faces={%{"Noto Sans Arabic" => "https://fonts.example.com/noto-arabic.woff2"}}
>

Each key of font_faces is a font name a symbol layer's text_font names, sent as written. Its value is the URL of a font file, or a list of faces, each a map with the url and the unicode_range it covers:

font_faces={%{"Noto Sans Regular" => [
  %{url: "/fonts/NotoSansKhmer-Regular.ttf", unicode_range: ["U+1780-17FF"]},
  %{url: "/fonts/NotoSansDevanagari-Regular.ttf", unicode_range: ["U+0900-097F"]}
]}}

MapLibre draws a character with the first face of its font that covers it, and takes the rest from the glyph server. It downloads a font file only once a character the file covers is drawn, and skips a face it cannot load or read, with a console warning.

Each replaces the style's own: font_faces is not merged with the font faces a style declares. Both belong to the style in MapLibre, which has no option for either. They are put in place once the first style has loaded, and as they change, with setGlyphs and setFontFaces, and each change lays the map's labels out again. A style change keeps them: every new style, whether MapLibre diffs it or builds it from scratch, has them put in place once it has loaded, before it draws, and after a WebGL context loss MapLibre builds the style with them. Set to nil, they go back to the style's own, or to none for a style without: with no glyphs, MapLibre draws text with the fonts the device has. A glyphs URL MapLibre refuses, one without its two tokens, is reported through on_error, and the map keeps the glyphs it had. Neither fires a map event.

Changing the style

style applies as it changes, compared by value, so an inline style rendered again unchanged does nothing. MapLibre diffs the new style against the one on the map, and the browser runtime carries every source, layer and HoloMap.Sprite the components declared into the new style, so only the basemap changes: the map does not go blank, sources both styles share keep their tiles, and a sprite and glyphs both styles use are not requested again. The components' layers keep their template order, a before_id names a layer of the new style, and each layer goes back to its props, losing whatever HoloMap.API set on it. Images, sprites, terrain, sky, the feature state of the components' sources, the global_state, the projection, glyphs and font_faces stay as they were, and HoloMap.Light's light is set again over the new style's own. A new style the diff finds nothing to change in leaves the map as it is, and one that fails MapLibre's validation is reported through on_error, or the browser console, and the map keeps the style it has.

A source, layer or sprite whose id the new style uses is the new style's, as on the first style: its component adds nothing, the layers of such a source stay off the map, and the browser runtime logs a warning naming them.

MapLibre builds the new style from scratch instead when it cannot diff it, for example when the new style sets centerAltitude, and when the change comes before the first style has loaded. The map then starts from an empty style, and the components' sources, layers, images, sprites, terrain, sky and light are declared again once it has loaded, over a style that starts with the global_state, and the projection, glyphs and font_faces are put in place again. HoloMap.API.set_style/3 with diff: false asks for that on purpose. Either way, changes and HoloMap.API calls made while the style changes wait for it.

Losing the WebGL context

A browser can take a page's WebGL context away, when the GPU resets or too many contexts are open, and give it back later. on_webgl_context_lost and on_webgl_context_restored report both. In between MapLibre has no style and draws nothing, and changes and HoloMap.API calls made meanwhile wait, as they do while a style changes. Once the context is back, MapLibre builds the style the map had again, from a copy it kept, and the components' sources, layers, images, sprites, terrain and sky are theirs as they were, with what HoloMap.API set on them. HoloMap.Light's light, which the copy leaves out, is set again. The global_state, the projection, glyphs and font_faces are the ones the map declares, a style changed meanwhile is then diffed against it, and a source, layer or sprite whose id the style held before stays the style's, without a second warning. Feature state is gone, and so is a global state value set through HoloMap.Runtime.call/3, as on a style MapLibre builds from scratch. A context lost while a style is still loading leaves MapLibre nothing to build again, and the map stays blank until its style changes.

Props read only when the map is built

MapLibre reads some options only while it builds the map, and has no setter to change them afterwards. The props table below marks them build only: hash, attribution_control, antialias, pitch_with_rotate, fade_duration, bearing_snap, track_resize, max_tile_cache_size, local_ideograph_font_family, validate_style, locale and worker_url. A change to one leaves the map as it was built, and the browser runtime logs a console warning that names the MapLibre option, once for each option on each map. A key of options is build only as well, unless it is the MapLibre name of an option that applies as it changes, such as "maxBounds", which then applies as its prop does.

Props

PropTypeAfter the map is builtNotes
stylestring or mapAppliesRequired. Style URL or inline style object. See Changing the style
center{lng, lat}AppliesCamera centre
zoom / bearing / pitchnumberAppliesCamera attitude
min_zoom / max_zoom / min_pitch / max_pitchnumberAppliesCamera constraints. nil lifts one
max_boundsboundsAppliesPan constraint, in any shape HoloMap.Spec.bounds/1 accepts. nil lifts it
interactivebooleanAppliesfalse for a static, non-navigable map. See Interaction
hashbooleanBuild onlySync the camera to the URL fragment
attribution_controlbooleanBuild onlyMapLibre's built-in attribution. See HoloMap.Control.Attribution to place it yourself
cooperative_gesturesbooleanAppliesRequire ctrl/⌘ to scroll-zoom, so the page still scrolls
drag_rotate / drag_pan / scroll_zoom / double_click_zoom / box_zoom / keyboard / touch_zoom_rotatebooleanAppliesIndividual interaction handlers
antialiasbooleanBuild onlyAsk the WebGL context for antialiasing, which smooths the edges of fill-extrusion layers. Sent as MapLibre's canvasContextAttributes
render_world_copiesbooleanAppliesDraw the world again beyond 180 degrees of longitude. Default true
pixel_rationumberAppliesRender at this ratio of canvas pixels to CSS pixels instead of the device's
projectionstring or listApplies"mercator", "globe", "vertical-perspective" or an expression. Wins over the style's projection. nil returns to it. See Projection
global_statemapAppliesValues the style's global-state expressions read, by name. A name set to nil or taken out goes back to the style's default. See Global state
glyphsstringAppliesGlyph server URL, with {fontstack} and {range}. Replaces the style's glyphs. nil returns to them. See Glyphs and font faces
font_facesmapAppliesFont files by font name, a URL or a list of %{url: url, unicode_range: ranges}. Replaces the style's font faces. nil returns to them. See Glyphs and font faces
fade_duration / bearing_snap / track_resize / pitch_with_rotate / max_tile_cache_size / local_ideograph_font_family / validate_style / localevariousBuild onlyPassed straight through to MapLibre
optionsmapBuild only, but see aboveRaw MapLibre constructor options, merged last. Keys must be MapLibre's own camelCase names: options={%{"maxCanvasSize" => [2048, 2048]}}. A "canvasContextAttributes" map given here is merged with antialias, and its keys win
worker_urlstringBuild onlyWhere the application serves maplibre-gl-worker.mjs. Default "/assets/maplibre-gl-worker.mjs?v=<MapLibre version>". See The worker URL
classstringAppliesCSS classes for the wrapper element
height / widthstringAppliesInline size for the canvas. nil opts out and leaves sizing to CSS

Event props

Each listens for the MapLibre event of the same name: on_dbl_click for dblclick, on_source_data_loading for sourcedataloading.

GroupProps
Lifecycleon_load, on_idle, on_error, on_resize, on_webgl_context_lost, on_webgl_context_restored
Loadingon_data, on_data_loading, on_data_abort, on_source_data, on_source_data_loading, on_source_data_abort, on_style_data, on_style_image_missing
Pointeron_click, on_dbl_click, on_context_menu, on_mouse_move, on_mouse_down, on_mouse_up, on_mouse_over, on_mouse_out, on_wheel, on_touch_start, on_touch_move, on_touch_end, on_touch_cancel, on_cooperative_gesture_prevented
Cameraon_move_start, on_move, on_move_end, on_zoom_start, on_zoom, on_zoom_end, on_rotate_start, on_rotate, on_rotate_end, on_pitch_start, on_pitch, on_pitch_end, on_roll_start, on_roll, on_roll_end, on_drag_start, on_drag, on_drag_end, on_box_zoom_start, on_box_zoom_end, on_box_zoom_cancel
Renderingon_render, on_projection_transition, on_terrain

MapLibre fires on_move, on_zoom, on_rotate, on_pitch, on_roll and on_drag on every frame of a move, and on_render on every frame it draws. Their handlers are throttled to 100 ms unless they name a throttle or a debounce of their own; the last event of a move always arrives (see "Throttling and debouncing" in HoloMap.Event).

Events

Handlers receive a payload with center, zoom, bearing, pitch and bounds, plus:

  • lng_lat and point for the mouse and touch events, where the pointer is, or the centre of the touches.

  • error for on_error: a map with the message, plus the status and url of a failed request and the source_id of a source's error when MapLibre reports them. The one exception is a map MapLibre could not build, below.

  • projection for on_projection_transition.

  • data_type for the loading events, "source" or "style", and for a source's, source_id, is_source_loaded, whether the source has no request left outstanding, and source_data_type: "metadata", "content", "visibility", "idle", or nil for a tile.

  • id for on_style_image_missing: the image a layer asked for that neither the style's sprite nor a HoloMap.Image holds.

  • gesture_type for on_cooperative_gesture_prevented: "wheel_zoom" or "touch_pan".

  • terrain for on_terrain: %{source: id, exaggeration: number}, or nil when terrain is taken away.

    def action(:map_moved, params, component) do put_state(component, :bounds, params.bounds) end

A loading state per source, from on_source_data_loading and on_source_data:

def action(:source_loading, %{source_id: id}, component) do
  put_state(component, :loading, Map.put(component.state.loading, id, true))
end

def action(:source_progress, %{source_id: id, is_source_loaded: true}, component) do
  put_state(component, :loading, Map.delete(component.state.loading, id))
end

def action(:source_progress, _params, component), do: component

A camera move the runtime makes for a camera prop is not reported, by any of the camera events. on_terrain reports every terrain MapLibre puts in place, HoloMap.Terrain's included, as on_projection_transition reports the projection prop's. See HoloMap.Event for the handler syntax and the Events guide for the full payload reference.

A map MapLibre cannot build

MapLibre draws with WebGL2. On a browser or device that cannot create a WebGL2 context, it cannot build the map at all, and the container stays empty. on_error receives that failure once, with MapLibre's message, "WebGL2 is required to display this map. ...", and its payload carries error alone: there is no camera to read center, zoom, bearing, pitch or bounds from. Camera limits MapLibre refuses when it builds the map, such as a min_zoom above max_zoom, are reported the same way. A map without on_error logs the error to the browser console.

The map is not built again while its container stays on the page, and the other maps on the page are built as usual. HoloMap.API calls made for it are dropped at once, with a console warning that names MapLibre's error, the ones queued for its boot among them. Telling the failure apart from the errors of a map that was built takes a match on the camera:

def action(:map_failed, %{center: _center} = params, component) do
  put_state(component, :notice, "The map reported: " <> params.error.message)
end

def action(:map_failed, params, component) do
  put_state(component, :notice, "This browser cannot show the map. " <> params.error.message)
end

Summary

Functions

Returns true to indicate that the callee module is a component module (has "use Hologram.Component" directive).

Returns the list of property definitions for the compiled component.

Functions

__is_hologram_component__()

@spec __is_hologram_component__() :: boolean()

Returns true to indicate that the callee module is a component module (has "use Hologram.Component" directive).

Examples

iex> __is_hologram_component__()
true

__props__()

@spec __props__() :: [{atom(), atom(), keyword()}]

Returns the list of property definitions for the compiled component.