Most of a map belongs in props. Some of it does not.
When to reach for it
"Fly to the result the user just picked" is an event, not a value.
Re-rendering the same centre twice should not re-animate, and animating is the
whole point. That is the category HoloMap.API exists for.
| Situation | Use |
|---|---|
| The camera reflects application state | HoloMap.Map's center / zoom props |
| The first view fits a box | HoloMap.Map's bounds and fit_bounds_options props |
| The camera should animate in response to an event | fly_to/2, ease_to/2 |
| A step of the camera from a button or a key | zoom_in/2, pan_by/3, rotate_to/3, reset_north/2 |
| A layer's paint reflects state | HoloMap.Layer.*'s paint prop |
| A one-off highlight your state does not track | set_paint_property/4 |
| Hover and selection styling | set_feature_state/3 |
| A question for the map, such as which features are in a box | query_rendered_features/2, request/4 |
| Zoom in on a clicked cluster | a layer's expand_cluster_on_click, or expand_cluster/4 |
| The points in a cluster | get_cluster_leaves/4 |
| A feed that sends the few features that changed | update_geojson/3, or a GeoJSON source's incremental |
| Let the user save the view as a file | download_image/2 |
| The view as an image in an action, for a report | export_image/2 |
An imperative change lasts until the reconciler sets the same thing from the
props. A paint or layout property is set again when that property's declared
value changes, a filter when the declared filter changes, the camera when
a declared center, zoom, bearing, pitch, roll or elevation changes,
in which case only the values that changed are set, and a GeoJSON source's
features when its declared data changes. A change to any other prop leaves the
imperative value in place, so an imperative fill-color survives a new
fill-opacity or filter. A layer that is added again, because its type,
source or source_layer changed or its source was rebuilt, comes back as
declared, and so does every layer when the style changes. The reconciler
treats rendered props as the source of truth.
Calling it
Always from an action, always with the map's cid first:
def action(:show_parcel, params, component) do
HoloMap.API.fly_to("explorer", center: {params.lng, params.lat}, zoom: 17)
put_state(component, :selected, params.id)
endActions only
These calls compile to no-ops on the server. They work in
action/3and in functions an action reaches; they do nothing ininit/3orcommand/3.To move the camera at mount time, chain an action from
init:def init(_params, component, _server) do component |> put_state(:style, @style_url) |> put_action(:frame_data) end
Calls made before the map has booted, or before its style finishes loading, are
queued and replayed in order, so an action scheduled from init is not lost,
even when it runs before the map's own boot action. Calls for a map that has not
booted within five seconds are dropped with a console warning. A call for a map
torn down with HoloMap.Runtime.destroy/1 while its container stays on the page
is dropped at once, with a warning, until the map boots again. So is a call for
a map MapLibre could not build, such as one on a browser without WebGL2, while
its container stays on the page: the warning names MapLibre's error, and the
calls queued for the map are dropped with it as soon as the map fails.
Camera
HoloMap.API.fly_to("explorer", center: {-70.66, 19.45}, zoom: 14, duration: 1_200)
HoloMap.API.ease_to("explorer", bearing: 45, pitch: 60)
HoloMap.API.jump_to("explorer", center: {-70.66, 19.45})
HoloMap.API.fit_bounds("explorer", [-71.0, 19.0, -70.0, 20.0], padding: 48)
HoloMap.API.resize("explorer")fly_to/2 arcs out and back in, which reads well over long distances.
ease_to/2 travels in a straight line, which reads better over short ones.
jump_to/2 does not animate, which is what a center prop change does.
:easing shapes an animated move's progress over its duration. MapLibre takes
it as a JavaScript function, which Elixir cannot send, so it takes the name of
one of CSS's timing curves, :linear, :ease_in, :ease_out or
:ease_in_out, or a curve of your own as {:cubic_bezier, x1, y1, x2, y2},
and the browser runtime builds the function. Anything else raises
ArgumentError. HoloMap.API.fly_to/2 documents each curve.
HoloMap.API.ease_to("explorer", bearing: 90, duration: 900, easing: :ease_in_out)
HoloMap.API.fly_to("explorer", center: {-70.66, 19.45}, easing: {:cubic_bezier, 0.3, 0, 0.2, 1})The three moves share their options, and each ignores the ones MapLibre's
method does not read: :roll turns the camera about the line it looks along,
:padding keeps pixels clear on a side of the viewport and stays once the move
ends, :around zooms ease_to/2 about a coordinate, and :elevation, which
only jump_to/2 sets, raises or lowers the centre above sea level. The table
in HoloMap.API.fly_to/2 lists every option and which move reads it. An option
none of them knows raises ArgumentError, so a misspelt one does not pass
unnoticed.
HoloMap.API.ease_to("explorer", zoom: 15, around: {-70.69, 19.45}, roll: 10)
HoloMap.API.fly_to("explorer", center: {-70.66, 19.45}, padding: %{left: 320}, min_zoom: 6)fit_bounds/3 accepts any shape HoloMap.Spec.bounds/1 understands: a pair of
corners, or a flat [west, south, east, north] list. Its :padding is added
to the map's own, unless absolute_padding: true makes it replace it, which
suits a side panel that covers part of the map:
HoloMap.API.fit_bounds("explorer", [-71.0, 19.0, -70.0, 20.0],
padding: %{left: 360, top: 20, right: 20, bottom: 20},
absolute_padding: true
)A map whose first view fits a box needs no call: HoloMap.Map's bounds prop
is fitted as MapLibre builds the map, with the options of fit_bounds/3 given
as fit_bounds_options. MapLibre reads both only then, so a box that changes
later is this call's to fit.
MapLibre's other camera methods each have a wrapper, which takes coordinates and pixel positions as tuples and its options as a keyword list, checked as the moves' are:
| Function | What it does |
|---|---|
pan_by/3 | Pans by an {x, y} number of pixels |
pan_to/3 | Pans to a coordinate |
zoom_to/3 | Zooms to a level, about the centre or a coordinate given as :around |
zoom_in/2, zoom_out/2 | Zooms in or out by one level |
rotate_to/3 | Turns the map to a bearing |
reset_north/2, reset_north_pitch/2 | Turns the map north up, and levels it too |
snap_to_north/2 | Turns the map north up if it is within bearing_snap of it |
stop/1 | Stops the move in progress where it is |
fit_screen_coordinates/5 | Fits the camera to a box drawn on the screen, at a bearing |
set_padding/2 | Sets the padding around the viewport, side by side |
set_roll/2, set_center_elevation/2, set_vertical_field_of_view/2 | Sets the roll, the centre's elevation or the field of view |
set_center_clamped_to_ground/2 | Says whether the centre follows the ground |
HoloMap.API.pan_by("explorer", {0, -200}, duration: 300)
HoloMap.API.zoom_to("explorer", 12, around: {-70.66, 19.45})
HoloMap.API.rotate_to("explorer", 90, easing: :ease_out)
HoloMap.API.reset_north("explorer")
HoloMap.API.set_padding("explorer", %{left: 320})
HoloMap.API.stop("explorer")The animated ones take the options of ease_to/2 that shape the move, less
the one their own argument stands for: zoom_to/3 takes no :zoom. zoom_in/2,
zoom_out/2 and the north resets take the options of an animation alone. A
move any of them makes is reported to the map's move events, as one fly_to/2
makes is. What the camera holds comes back through request/4, below:
"getRoll", "getPadding", "getCenterElevation", "getVerticalFieldOfView"
and "getCenterClampedToGround" answer with plain values.
resize/1 is almost never needed. MapLibre observes its own container, so a map
whose container changes size follows along by itself and this call does nothing.
The one case where it is required is a map built with track_resize={false},
which switches that observer off; the demo's camera page has one set up that way
so the difference is visible.
Layers
HoloMap.API.set_filter("explorer", "parcels-fill", ["==", ["get", "zone"], "R1"])
HoloMap.API.set_paint_property("explorer", "parcels-fill", :fill_color, "#ef4444")
HoloMap.API.set_layout_property("explorer", "parcels-fill", :visibility, "none")Property names may be atoms in Elixir style or MapLibre specification names; both reach MapLibre as the latter.
These duplicate what the paint, layout and filter props already do, and in
almost every case the props are the better choice: a style change, or a
structural source change that adds a layer again, gives the layer its props
back, and loses whatever was set here. Reach here for something genuinely
transient.
Feature state
Feature state is the mechanism behind hover and selection styling, and it has no declarative equivalent: it belongs to a feature, not to a component.
HoloMap.API.set_feature_state("explorer", %{source: "parcels", id: 12}, %{hover: true})
HoloMap.API.remove_feature_state("explorer", %{source: "parcels", id: 12}, "hover")
HoloMap.API.remove_feature_state("explorer", %{source: "parcels", id: 12})Add :source_layer for a vector source. Every feature needs an id, which GeoJSON
features often lack. Set generate_id on the source, or point promote_id at
a property that is already unique. There is a worked example in
Events.
Feature state lasts as long as the source does. A style change MapLibre diffs
keeps it on the sources the components declared. One it builds from scratch
clears it, as a structural change to the source does, and so does a WebGL
context loss, after which MapLibre builds the style again: set it again from
on_webgl_context_restored if it matters.
Clusters
A clustered HoloMap.Source.GeoJSON gathers nearby points into clusters, each
a feature with cluster: true, a cluster_id and a point_count in its
properties. The usual way to open one up is a click that zooms in to where it
breaks apart, which a layer does by itself with expand_cluster_on_click.
expand_cluster/4 makes the same move from an action, with the options of
ease_to/2:
def action(:cluster_clicked, params, component) do
case params.features do
[%{properties: %{cluster_id: id}, geometry: %{coordinates: point}} | _rest] ->
HoloMap.API.expand_cluster("explorer", "stops", id, center: point, duration: 300)
_not_a_cluster ->
:ok
end
component
endWithout :center, the camera zooms in about its current centre. The cluster's
point, the feature's geometry.coordinates, brings it to the middle.
The points inside a cluster, for a list or a popup, come back through the reply channel described below, as features:
HoloMap.API.get_cluster_leaves("explorer", "stops", id, limit: 20, reply: :leaves_loaded)
def action(:leaves_loaded, %{result: leaves, truncated: more}, component) do
put_state(component, leaves: leaves, more: more)
end:limit is how many points the answer holds, 100 unless given, and :offset
how many it skips. While truncated is true, the next page starts at
offset + limit. get_cluster_children/4 answers with what the cluster
breaks into at the next zoom instead: smaller clusters and single points.
GeoJSON features
When the application already knows which features changed, such as a feed
that sends the vehicles that moved, update_geojson/3 hands MapLibre's
updateData the change alone, without touching the source's data prop:
HoloMap.API.update_geojson("fleet-map", "fleet",
add: [feature],
update: [%{id: 7, new_geometry: %{type: "Point", coordinates: [-70.1, 19.2]}}],
remove: [3]
)The diff names features by id, the property promote_id names or each
feature's own id, so every feature of the source needs one. The source
keeps the change through style changes and a lost WebGL context, and through
renders that leave data as the previous render had it, until its data
prop changes. That change wins: the source then holds exactly the new
data. With incremental, the reconciler sends it as a diff from what the
source holds, this call's changes included; without it, the data is set
whole. HoloMap.Source.GeoJSON's "Changing a few features" covers
incremental, which sends each data change as a diff without this call.
Asking the map
The calls above tell the map to do something, and return :ok at once. A
question, such as which features are in a box or where a coordinate is on
screen, has an answer, and the answer lives in the browser. So a question
names the action that receives it, with :reply, and the answer arrives
there as that action's params:
def action(:select_in_box, params, component) do
HoloMap.API.query_rendered_features("explorer",
box: {{params.x1, params.y1}, {params.x2, params.y2}},
layers: ["parcels-fill"],
reply: :parcels_found
)
component
end
def action(:parcels_found, %{error: error}, component) do
put_state(component, :notice, error.message)
end
def action(:parcels_found, %{result: features, truncated: truncated}, component) do
component
|> put_state(:selection, features)
|> put_state(:more_than_shown, truncated)
end:reply takes the shapes an event prop takes: an action name, which goes to
the page, or %{action: ..., target: ..., params: ...} for an action on a
component. Its params are merged under the answer, so an application that
sends several questions to one action can tell the answers apart:
HoloMap.API.request("explorer", "getZoom", [], reply: %{action: :read, params: %{ref: "zoom"}})
HoloMap.API.request("explorer", "getBounds", [], reply: %{action: :read, params: %{ref: "bounds"}})
def action(:read, %{ref: "zoom", result: zoom}, component), do: put_state(component, :zoom, zoom)
def action(:read, %{ref: "bounds", result: bounds}, component), do: put_state(component, :bounds, bounds)The params travel as JSON, as an event prop's do, so an atom among their values comes back as a string.
The answer's params hold one of two keys:
:result, the answer as plain data. Coordinates are[lng, lat]lists, pixel positions[x, y], and bounds[[west, south], [east, north]], as in event payloads, and features are maps withid,source,source_layer,propertiesandgeometry, as layer events carry them.:error,%{message: message}, when MapLibre throws or reports an error while it answers, such as for a layer the style does not hold (which the map'son_errorhears as well), or when there is no map to answer: it did not boot within five seconds, MapLibre could not build it, orHoloMap.Runtime.destroy/1tore it down before it answered.
| Question | Function | :result |
|---|---|---|
| Features MapLibre rendered, in the viewport, at a point or in a box | query_rendered_features/2 | features |
| Features a source holds, rendered or not | query_source_features/3 | features |
| Where a coordinate is on screen | project/3 | [x, y] |
| The coordinate at a pixel position | unproject/3 | [lng, lat] |
| The terrain's elevation at a coordinate | query_terrain_elevation/3 | metres, or nil without terrain |
| The camera that fits a box | camera_for_bounds/3 | %{center: [lng, lat], zoom: z, bearing: b}, with padding: %{...} for absolute_padding: true, or nil |
| A feature's state | get_feature_state/3 | a map |
| The points in a cluster, a page at a time | get_cluster_leaves/4 | features |
| What a cluster breaks into at the next zoom | get_cluster_children/4 | features |
| Anything else, by method name | request/4 | see HoloMap.API.request/4 |
request/4 reaches any method of the map, and with :source any method of
one of its sources, including one that returns a promise, which is answered
when the promise settles. Its documentation lists what the getters MapLibre
has, such as getCenter, getStyle, listImages and areTilesLoaded,
answer.
How big an answer can be
An answer crosses into Elixir as an action's params, which Hologram builds
term by term in the browser, so a large answer costs time on every request.
A query for features is bounded: its answer carries at most 100 features,
or the number given with :limit, and truncated: true says some were left
out. geometry: false leaves out each feature's geometry, usually most of a
feature's size, when the application needs only ids and properties. Other
answers are as big as what they describe: a camera, a list of ids, a feature's
state. getStyle is the exception, as it carries the whole style, inline
GeoJSON data included.
When the answer arrives
A question waits, as a call does, for a map that has not booted and for a
style that is loading, and is answered after the calls made before it. So
set_feature_state/3 followed by get_feature_state/3 reads the state just
set, and a query made while a new style loads finds the new style's features.
A map that fails to build, or that HoloMap.Runtime.destroy/1 tears down,
answers with an :error rather than leaving the action waiting. Once a
navigation has taken the page away, an answer still on its way is dropped:
the page that asked is not there to hear it.
Exporting the view
download_image/2 saves what the map shows as an image file, from the
browser, as any download is saved. Nothing crosses into Elixir:
def action(:download_map, _params, component) do
HoloMap.API.download_image("explorer", filename: "parcels.png")
component
endexport_image/2 brings the image to an action instead, as a data: URL,
for a report or a preview. It is a question, so it takes a :reply, and the
browser measures the data URL before it sends anything: one longer than
:max_bytes, a million bytes unless set, is answered with an :error, and
the image stays in the browser.
def action(:snapshot, _params, component) do
HoloMap.API.export_image("explorer",
reply: :snapshot_ready,
format: "image/jpeg",
quality: 0.8,
max_bytes: 2_000_000
)
component
end
def action(:snapshot_ready, %{result: %{data_url: url, width: width, height: height}}, component) do
put_state(component, :snapshot, %{url: url, width: width, height: height})
end
def action(:snapshot_ready, %{error: error}, component) do
put_state(component, :notice, error.message)
endBoth take :format, "image/png", "image/jpeg" or "image/webp", and
:quality for the last two. A data URL holds the image in base64, a third
bigger than the image, and a JPEG is usually far smaller than a PNG of the
same view.
The image is the map's canvas: what MapLibre draws with WebGL, at the canvas's size in pixels, which is the map's size on the page times the pixel ratio. Markers, popups, controls and the attribution are elements of the page, and are not in it. Map data whose licence asks for attribution, as OpenStreetMap's does, needs that attribution wherever the image is shown or printed: add the text next to the image, or into the report it goes in.
MapLibre's canvas keeps a frame only until the browser has shown it, so the
browser runtime asks for a frame and reads the canvas as MapLibre finishes
it; the map needs no preserveDrawingBuffer. Both wait, as the other calls
do, for the map to boot and for its style.
Anything else
HoloMap.Runtime.call/3 reaches any method on the underlying maplibregl.Map:
HoloMap.Runtime.call("explorer", "setRenderWorldCopies", [false])It queues against style readiness like everything else, but it does not
normalise its arguments, and whatever the method returns is discarded. Use
HoloMap.API.request/4 for a method whose answer you need.
The arguments cross into the browser as JSON, as every HoloMap.API call's
do. An atom arrives as its name, so :top reaches MapLibre as "top" rather
than as the browser's window.top, which Hologram's interop would make of it.
A tuple arrives as a list and nil as null. A struct, a function or a pid
raises ArgumentError: a JavaScript object, such as an image element, belongs
in your own JavaScript, through the map window.HoloMap.map(cid) returns.
From JavaScript
A MapLibre plugin (a draw control, a geocoder, a deck.gl overlay) needs the
raw map object, and Hologram's interop cannot hand one to a third-party script.
Every booted map is published on window:
window.HoloMap.map("explorer") // the maplibregl.Map, or null
window.HoloMap.cids() // every live map's cid
window.HoloMap.destroy("explorer") // release its WebGL contextPrefer HoloMap.API from Elixir: it queues correctly against the style's
readiness, which a raw handle does not.
The runtime puts these on window.HoloMap as soon as it loads. A page that
registers JavaScript makes window.HoloMap earlier, holding only registry,
so code that may run before the runtime has loaded asks
window.HoloMap?.map?.("explorer").
What you add through the raw handle is outside the reconciler, so a style change can take it away. JavaScript that MapLibre takes as an option or an object, such as a protocol, is better registered by name and referred to from Elixir: see Registering JavaScript.