HoloMap.API (HoloMap v0.4.0)

Copy Markdown View Source

Imperative commands for things that are not state.

Most of a map belongs in component props: which layers exist, how they are painted, what the camera is looking at. Some of it does not. "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.

These functions are for that second category. Call them from an action:

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)
end

The first argument is always the map's cid, the same string given to HoloMap.Map.

Most of these return :ok and send nothing back. The ones that ask the map something, such as query_rendered_features/2 and request/4, take a :reply naming the action that receives the answer. The Imperative API guide explains the pattern.

Actions only

These calls compile to no-ops on the server. They work in action/3 and in functions an action reaches; they do nothing in init/3 or command/3.

Choosing between this and props

SituationUse
The camera reflects application stateHoloMap.Map's center/zoom props
The camera should animate in response to an eventfly_to/2, ease_to/2
A step of the camera from a button or a keyzoom_in/2, pan_by/3, rotate_to/3, reset_north/2
A side panel covers part of the mapset_padding/2, or fit_bounds/3 with :absolute_padding
A layer's paint reflects stateHoloMap.Layer.*'s paint prop
A one-off highlight your state does not trackset_paint_property/4
A question for the map, such as which features are in a boxquery_rendered_features/2, request/4
Zoom in on a clicked clustera layer's expand_cluster_on_click, or expand_cluster/4
The points in a clusterget_cluster_leaves/4
A feed that sends the few features that changedupdate_geojson/3
Locate the user from an actiontrigger_geolocate/1
Let the user save the view as a filedownload_image/2
The view as an image in an actionexport_image/2

An imperative change lasts until the reconciler sets the same thing from the props: a paint or layout property when that property's declared value changes, a filter when the declared filter changes, and the camera when a declared center, zoom, bearing, pitch, roll or elevation changes, which sets only the values that changed, and a GeoJSON source's features when its declared data changes. A change to any other prop leaves it 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 the rendered props as the source of truth.

Summary

Functions

Finds the camera that fits a bounding box, without moving to it, and dispatches it to an action.

Saves the map's current view as an image file, from the browser.

Animates the camera along a straight path, without the zoom-out arc.

Zooms in to where a cluster breaks apart.

Reads the map's current view as an image, and dispatches it to an action as a data URL, if it is no bigger than :max_bytes.

Fits the camera to a bounding box.

Fits the camera to a box drawn on the screen, turned to bearing.

Animates the camera along a curved flight path.

Reads what a cluster breaks into at the next zoom, and dispatches it to an action.

Reads the points a cluster holds, and dispatches them to an action.

Reads a feature's state, and dispatches it to an action.

Moves the camera with no animation at all.

Pans the map by a number of pixels, with an animated move.

Pans the map to a coordinate, with an animated move.

Finds where a coordinate is on screen, and dispatches it to an action.

Finds the features MapLibre has rendered, and dispatches them to an action.

Finds the features a source holds, whether or not they are rendered, and dispatches them to an action.

Finds the terrain's elevation at a coordinate, and dispatches it to an action.

Asks the map for something, and dispatches the answer to an action.

Rotates the map back to north up, over a second unless :duration says otherwise. Takes the options zoom_in/2 takes.

Rotates the map back to north up and levels it: bearing, pitch and roll back to 0, over a second unless :duration says otherwise. Takes the options zoom_in/2 takes.

Recomputes the map's size after its container has been resized.

Rotates the map to a bearing, with an animated move.

Says whether MapLibre keeps the map's centre on the ground.

Sets the elevation of the map's centre, in metres above sea level, with no animation, as jump_to/2 with :elevation does.

Attaches feature state, the mechanism behind hover and selection styling.

Sets a layer's filter, or clears it when filter is nil.

Sets one layout property on a layer.

Sets the padding around the viewport, in pixels, with no animation.

Sets one paint property on a layer.

Sets the camera's roll, in degrees, with no animation: its turn about the line it looks along. jump_to/2 with :roll does the same, and fly_to/2 and ease_to/2 animate it.

Replaces the whole style.

Sets the camera's vertical field of view, in degrees, with no animation.

Rotates the map back to north up when its bearing is already close to it, within HoloMap.Map's bearing_snap, 7 degrees unless set, and leaves it as it is otherwise. Takes the options zoom_in/2 takes.

Stops the camera move in progress where it is.

Asks for the user's position, as a click on the map's HoloMap.Control.Geolocate button does.

Finds the coordinate at a pixel position, and dispatches it to an action.

Changes some features of a HoloMap.Source.GeoJSON, without changing its data prop.

Zooms in by one level, with an animated move.

Zooms out by one level, with an animated move. Takes the options zoom_in/2 takes.

Zooms the map to a zoom level, with an animated move.

Functions

camera_for_bounds(cid, bounds, opts)

@spec camera_for_bounds(String.t(), term(), keyword()) :: :ok

Finds the camera that fits a bounding box, without moving to it, and dispatches it to an action.

bounds takes any shape HoloMap.Spec.bounds/1 understands. The answer's :result is %{center: [lng, lat], zoom: zoom, bearing: bearing}, which jump_to/2 or fly_to/2 can move to, or nil when the padding leaves no room for the box.

HoloMap.API.camera_for_bounds("explorer", [-71.0, 19.0, -70.0, 20.0],
  padding: 40,
  reply: :camera_found
)

Options

  • :reply - required; see request/4.
  • :padding - pixels to keep clear around the box: a number, or a map with :top, :bottom, :left and :right, on top of the map's own padding.
  • :absolute_padding - true fits the box with :padding in place of the map's padding, and the answer carries that padding as well, as %{top: t, bottom: b, left: l, right: r}, for jump_to/2 or fly_to/2 to move to with the camera.
  • :offset - an {x, y} pixel offset of the box's centre from the map's.
  • :max_zoom - the highest zoom the camera may have.
  • :bearing - the bearing to fit the box at.

Any other option raises ArgumentError.

download_image(cid, opts \\ [])

@spec download_image(
  String.t(),
  keyword()
) :: :ok

Saves the map's current view as an image file, from the browser.

def action(:download_map, _params, component) do
  HoloMap.API.download_image("explorer", filename: "parcels.png")
  component
end

The browser saves the file as it saves any download, and nothing crosses into Elixir, whatever the image's size. To get the image in an action instead, use export_image/2.

Options

  • :filename - the name the browser offers the file under. Defaults to the map's cid with the format's extension, such as "explorer.png".
  • :format - "image/png", the default, "image/jpeg" or "image/webp". A browser that cannot write the format writes a PNG.
  • :quality - for "image/jpeg" and "image/webp", a number from 0 to
    1. Left out, the browser picks its own.

An option it does not take raises ArgumentError, and so does a value it does not take.

What the image holds

The image is the map's canvas, at its size in pixels: the size the map takes on the page times the device's pixel ratio, or HoloMap.Map's pixel_ratio. It holds what MapLibre draws with WebGL. Markers, popups, controls and the attribution are elements of the page and are not in it, so an image of map data whose licence asks for attribution, as OpenStreetMap's does, needs the attribution added where the image is used.

MapLibre's WebGL context keeps a frame only until the browser has shown it, so the browser runtime asks MapLibre for a frame and reads the canvas as MapLibre finishes drawing it: no preserveDrawingBuffer is needed. A failure, such as a canvas the browser makes no image of, is reported through the map's on_error, or the browser console. Like the other calls, it waits for the map to boot and for a style to load.

ease_to(cid, opts)

@spec ease_to(
  String.t(),
  keyword()
) :: :ok

Animates the camera along a straight path, without the zoom-out arc.

Takes the options of fly_to/2, and ignores the flight's own, :speed, :curve, :screen_speed, :max_duration and :min_zoom, and :elevation. :around zooms about a coordinate:

HoloMap.API.ease_to("explorer", zoom: 15, around: {-70.69, 19.45}, duration: 600)

expand_cluster(cid, source_id, cluster_id, opts \\ [])

@spec expand_cluster(String.t(), String.t(), integer(), keyword()) :: :ok

Zooms in to where a cluster breaks apart.

Eases the camera to the zoom at which the cluster cluster_id of the clustered HoloMap.Source.GeoJSON source_id breaks apart, as MapLibre's getClusterExpansionZoom works it out. cluster_id is the cluster_id property of a cluster feature, as a layer event carries it:

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
end

A layer's expand_cluster_on_click does the same with no action, with MapLibre's default move (see "Expanding clusters" in HoloMap.Layer).

Options

The options of ease_to/2 that shape the move: :center, :bearing, :pitch, :duration, :easing, :offset, :padding, :animate and :essential. Without :center, the camera zooms in about its current centre; give the cluster's point, a layer event's feature's geometry.coordinates, to bring the cluster to the middle. :zoom is the cluster's and raises ArgumentError, as does any other option.

The source's worker works the zoom out, so the camera moves a moment after the call, and the move is reported to the map's move events, as one ease_to/2 makes is. A source the map lacks, one that is not clustered, and a source that refuses the question log a console warning, and the camera stays put. Like the other calls, it waits for the map to boot and for a style to load.

export_image(cid, opts)

@spec export_image(
  String.t(),
  keyword()
) :: :ok

Reads the map's current view as an image, and dispatches it to an action as a data URL, if it is no bigger than :max_bytes.

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: image}, component) do
  put_state(component, :snapshot, image.data_url)
end

def action(:snapshot_ready, %{error: error}, component) do
  put_state(component, :notice, error.message)
end

Options

  • :reply - required. The action that receives the image; see request/4.
  • :format - "image/png", the default, "image/jpeg" or "image/webp".
  • :quality - for "image/jpeg" and "image/webp", a number from 0 to
    1. Left out, the browser picks its own.
  • :max_bytes - the most bytes the data URL may hold, a positive integer. Defaults to 1000000.

An option it does not take raises ArgumentError, and so does a value it does not take.

The answer

:result is a map with :data_url, the image as a data: URL, :format, the format the browser wrote, which is "image/png" for a format it cannot write, and :width and :height, the image's size in pixels.

The browser runtime measures the data URL before anything is sent, and a data URL longer than :max_bytes is answered with an :error that says how big it was, the image left in the browser. A data URL holds the image in base64, which takes a third more bytes than the image itself. A JPEG or a WebP is usually far smaller than a PNG of the same view; a map at a high pixel ratio is far bigger than one at 1. For a file the user keeps, without the image crossing into Elixir, use download_image/2.

An :error also comes for a canvas the browser makes no image of, and whenever request/4 answers with one, such as a map that never booted. The image holds what download_image/2 says, MapLibre's canvas alone, without the attribution, and waits as a request does.

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

@spec fit_bounds(String.t(), term(), keyword()) :: :ok

Fits the camera to a bounding box.

bounds accepts any shape HoloMap.Spec.bounds/1 understands: a pair of corners, or a flat [west, south, east, north] list.

HoloMap.API.fit_bounds("explorer", [-71.0, 19.0, -70.0, 20.0], padding: 48)

MapLibre works out the camera that fits the box, as camera_for_bounds/3 answers it, and flies there, as fly_to/2 does, or with linear: true eases there, as ease_to/2 does.

Options

  • :padding - pixels to keep clear around the box: a number, or a map with :top, :bottom, :left and :right. MapLibre adds it to the map's own padding.
  • :absolute_padding - true makes :padding replace the map's padding instead, and the map keeps it once the move ends. MapLibre 7 is to make this the default.
  • :max_zoom - the highest zoom the fit may reach.
  • :bearing - the bearing to fit the box at. :pitch and :roll are the camera's once it has moved.
  • :linear - true eases to the box rather than flying.
  • :offset - an {x, y} pixel offset of the box's centre from the map's.
  • The options that shape the move, as fly_to/2 documents them: :duration, :easing, :animate, :essential, :freeze_elevation, and for a flight :speed, :curve, :screen_speed, :max_duration and :min_zoom.

The fit decides the centre and the zoom, so :center and :zoom raise ArgumentError, as does any other option, and an :easing or :offset fly_to/2 refuses.

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,
  easing: :ease_out
)

fit_screen_coordinates(cid, first, second, bearing, opts \\ [])

@spec fit_screen_coordinates(
  String.t(),
  {number(), number()} | [number()],
  {number(), number()} | [number()],
  number(),
  keyword()
) :: :ok

Fits the camera to a box drawn on the screen, turned to bearing.

first and second are {x, y} pixel positions relative to the map's container, opposite corners of the box, as an event's point is. The camera moves so that the ground the box covers fills the viewport, turned to bearing, as fit_bounds/3 fits a box of coordinates.

HoloMap.API.fit_screen_coordinates("explorer", {40, 60}, {400, 300}, 0, padding: 20)

Takes the options of fit_bounds/3, except :bearing, which bearing is. Any other option raises ArgumentError, as do corners that are not pixel positions and a bearing that is not a number.

fly_to(cid, opts)

@spec fly_to(
  String.t(),
  keyword()
) :: :ok

Animates the camera along a curved flight path.

HoloMap.API.fly_to("explorer", center: {-70.66, 19.45}, zoom: 14, duration: 1_200)

Options

fly_to/2, ease_to/2 and jump_to/2 take the same options. Each ignores the ones MapLibre's method does not read, as the third column says.

OptionValueRead by
:centera coordinate, in any shape HoloMap.Spec.lng_lat/1 acceptsall three
:zoom / :bearing / :pitcha numberall three
:rolla number of degrees, the camera's turn about the line it looks alongall three
:elevationthe centre's elevation, in metres above sea leveljump_to/2 only: MapLibre's flyTo and easeTo ignore it
:paddingpixels kept clear on each side of the viewport, a map with :top, :bottom, :left and :right. Those left out keep the map's. The map keeps the new padding after the moveall three
:arounda coordinate that keeps its place on screen while the camera zooms about it, in place of :centerease_to/2 only
:durationmillisecondsfly_to/2, ease_to/2
:easinga named curve, belowfly_to/2, ease_to/2
:offsetan {x, y} pixel offset of the target centre from the map'sfly_to/2, ease_to/2
:animatefalse moves without animatingfly_to/2, ease_to/2
:essentialtrue animates even when the user's system asks for reduced motionfly_to/2, ease_to/2
:freeze_elevationtrue keeps the camera at a constant height above sea level over terrain, and works the zoom out once the move endsfly_to/2, ease_to/2
:speed / :curve / :screen_speedthe flight's speed, the height of its arc, and its speed in screenfuls per second, which wins over :speedfly_to/2 only
:max_durationmilliseconds; a flight that would last longer jumps insteadfly_to/2 only
:min_zoomthe lowest zoom the flight's arc may reachfly_to/2 only

Any other option raises ArgumentError, before anything is sent, and so do a :center or :around that is not a coordinate, an :offset that is not an {x, y} pair of numbers and an :easing that is not one of those below. :absolute_padding belongs to fit_bounds/3: these moves always replace the map's padding with the one given.

Easing

:easing shapes the animation's progress over its duration. It takes one of CSS's timing curves by name, or a cubic Bézier curve:

ValueCurve
:linearConstant speed
:ease_inStarts slowly, CSS's ease-in: cubic-bezier(0.42, 0, 1, 1)
:ease_outEnds slowly, CSS's ease-out: cubic-bezier(0, 0, 0.58, 1)
:ease_in_outStarts and ends slowly, CSS's ease-in-out: cubic-bezier(0.42, 0, 0.58, 1)
{:cubic_bezier, x1, y1, x2, y2}The curve CSS's cubic-bezier(x1, y1, x2, y2) describes. x1 and x2 are times and lie between 0 and 1; y1 and y2 may leave that range, for a move that overshoots
HoloMap.API.ease_to("explorer", bearing: 90, duration: 900, easing: :ease_in_out)

Left out, MapLibre eases the move its own way, along cubic-bezier(0.25, 0.1, 0.25, 1). Any other value raises ArgumentError: MapLibre takes the easing as a JavaScript function, which cannot be sent from Elixir, so the browser runtime builds it from one of these.

get_cluster_children(cid, source_id, cluster_id, opts)

@spec get_cluster_children(String.t(), String.t(), integer(), keyword()) :: :ok

Reads what a cluster breaks into at the next zoom, and dispatches it to an action.

cluster_id is the cluster_id property of a cluster of the clustered HoloMap.Source.GeoJSON source_id. The answer holds the smaller clusters and the single points the cluster breaks into, as layer events carry features, each with source_id as its source. A cluster among them has cluster: true, its own cluster_id and its point_count in its properties.

HoloMap.API.get_cluster_children("explorer", "stops", cluster_id, reply: :children_read)

Takes :reply, :limit and :geometry, as get_cluster_leaves/4 does, and raises ArgumentError for any other option. An :error arrives as it does there.

get_cluster_leaves(cid, source_id, cluster_id, opts)

@spec get_cluster_leaves(String.t(), String.t(), integer(), keyword()) :: :ok

Reads the points a cluster holds, and dispatches them to an action.

cluster_id is the cluster_id property of a cluster of the clustered HoloMap.Source.GeoJSON source_id, as layer events carry it. The answer holds the points as layer events carry features, each with source_id as its source, and :truncated says whether the cluster holds more points after them:

HoloMap.API.get_cluster_leaves("explorer", "stops", cluster_id,
  limit: 20,
  reply: :leaves_loaded
)

def action(:leaves_loaded, %{result: leaves, truncated: more}, component) do
  names = Enum.map(leaves, fn leaf -> leaf.properties.name end)
  put_state(component, leaves: names, more: more)
end

Options

  • :reply - required. The action that receives the points; see request/4.
  • :limit - the most points the answer carries, a positive integer; defaults to 100. It is the limit MapLibre's getClusterLeaves takes: the answer holds the points from :offset on, at most :limit of them.
  • :offset - how many of the cluster's points to skip, a non-negative integer; defaults to 0. While :truncated is true, the next page starts at offset + limit.
  • :geometry - false leaves each point's geometry out.

Any other option raises ArgumentError. An :error arrives instead for a cluster_id that names no cluster, a source the map lacks, and a source that is not clustered.

get_feature_state(cid, feature, opts)

@spec get_feature_state(String.t(), map() | keyword(), keyword()) :: :ok

Reads a feature's state, and dispatches it to an action.

feature identifies the feature as for set_feature_state/3. The answer's :result is the state as a map, empty for a feature with none, and an :error arrives instead for a source the map lacks. Takes only :reply.

HoloMap.API.get_feature_state("explorer", %{source: "parcels", id: 12}, reply: :state_read)

jump_to(cid, opts)

@spec jump_to(
  String.t(),
  keyword()
) :: :ok

Moves the camera with no animation at all.

Takes the same options as fly_to/2. Those that shape an animation, such as :duration and :easing, have no effect, though an :easing that is not one of the documented values still raises. It is the one of the three that sets :elevation:

HoloMap.API.jump_to("alps", center: {7.66, 45.98}, elevation: 4_478, pitch: 60)

pan_by(cid, offset, opts \\ [])

@spec pan_by(String.t(), {number(), number()} | [number()], keyword()) :: :ok

Pans the map by a number of pixels, with an animated move.

offset is an {x, y} pixel distance: {0, -200} brings into view what lies 200 pixels above the centre.

HoloMap.API.pan_by("explorer", {0, -200}, duration: 300)

Takes the options of ease_to/2 that shape the move, except :center and :offset, which the pan decides: :zoom, :bearing, :pitch, :roll, :padding, :around, :duration, :easing, :animate, :essential and :freeze_elevation. Any other option raises ArgumentError, as does an offset that is not an {x, y} pair of numbers.

pan_to(cid, lng_lat, opts \\ [])

@spec pan_to(String.t(), HoloMap.Spec.lng_lat(), keyword()) :: :ok

Pans the map to a coordinate, with an animated move.

lng_lat takes any shape HoloMap.Spec.lng_lat/1 understands.

HoloMap.API.pan_to("explorer", {-70.66, 19.45})

Takes the options of ease_to/2 that shape the move, except :center, which lng_lat is: :zoom, :bearing, :pitch, :roll, :padding, :around, :offset, :duration, :easing, :animate, :essential and :freeze_elevation. Any other option raises ArgumentError.

project(cid, lng_lat, opts)

@spec project(String.t(), HoloMap.Spec.lng_lat(), keyword()) :: :ok

Finds where a coordinate is on screen, and dispatches it to an action.

lng_lat takes any shape HoloMap.Spec.lng_lat/1 understands. The answer's :result is the [x, y] pixel position relative to the map's container. Takes only :reply.

HoloMap.API.project("explorer", {-70.69, 19.45}, reply: :placed)

query_rendered_features(cid, opts)

@spec query_rendered_features(
  String.t(),
  keyword()
) :: :ok

Finds the features MapLibre has rendered, and dispatches them to an action.

Without :point or :box, it looks at the whole viewport. Pixel positions are relative to the map's container, as an event's point is.

HoloMap.API.query_rendered_features("explorer",
  box: {{0, 0}, {320, 240}},
  layers: ["parcels-fill"],
  reply: :parcels_found
)

def action(:parcels_found, %{result: features, truncated: truncated}, component) do
  component
  |> put_state(:selection, features)
  |> put_state(:more, truncated)
end

Options

  • :reply - required. The action that receives the features; see request/4.
  • :point - an {x, y} pixel position, to find the features under it.
  • :box - two {x, y} pixel positions, opposite corners of a box, to find the features in it.
  • :layers - layer ids, to find only the features drawn in them.
  • :filter - a filter expression the features must match.
  • :limit - the most features the answer carries; defaults to 100.
  • :geometry - false leaves each feature's geometry out.

The answer's :result is a list of features as layer events carry them, :truncated says whether any were left out, and an :error arrives instead for a layer the style does not hold. Features are what MapLibre rendered: a feature drawn across tiles can come more than once.

:point and :box together raise ArgumentError, as does any other option.

query_source_features(cid, source_id, opts)

@spec query_source_features(String.t(), String.t(), keyword()) :: :ok

Finds the features a source holds, whether or not they are rendered, and dispatches them to an action.

MapLibre looks in the tiles it has loaded, which cover the viewport, so a feature that crosses tiles can come more than once. A vector source needs :source_layer.

HoloMap.API.query_source_features("explorer", "parcels",
  filter: ["==", ["get", "zone"], "R1"],
  reply: :zone_listed
)

Options

  • :reply - required. The action that receives the features; see request/4.
  • :source_layer - the layer of a vector source to look in.
  • :filter - a filter expression the features must match.
  • :limit - the most features the answer carries; defaults to 100.
  • :geometry - false leaves each feature's geometry out.

The answer is as for query_rendered_features/2. Each feature carries source_id as its source, and :source_layer as its source_layer, which MapLibre leaves off the features this query finds. A source the map lacks finds nothing.

query_terrain_elevation(cid, lng_lat, opts)

@spec query_terrain_elevation(String.t(), HoloMap.Spec.lng_lat(), keyword()) :: :ok

Finds the terrain's elevation at a coordinate, and dispatches it to an action.

The answer's :result is the elevation in metres, multiplied by the terrain's exaggeration, or nil when the map has no terrain. MapLibre reads it from the terrain tiles it has loaded, so a coordinate off screen can answer nil or a coarse value. Takes only :reply.

HoloMap.API.query_terrain_elevation("alps", {7.66, 45.98}, reply: :elevation_read)

remove_feature_state(cid, feature, key \\ nil)

@spec remove_feature_state(String.t(), map(), String.t() | nil) :: :ok

Clears feature state.

Omit key to clear every state entry on the feature.

request(cid, method, args, opts)

@spec request(String.t(), String.t(), list(), keyword()) :: :ok

Asks the map for something, and dispatches the answer to an action.

method names a method of MapLibre's maplibregl.Map, or with :source of one of its sources, and args its arguments, as HoloMap.Runtime.call/3 takes them. The answer comes back to the :reply action, whose params hold it:

HoloMap.API.request("explorer", "getZoom", [], reply: :zoom_read)

def action(:zoom_read, %{result: zoom}, component) do
  put_state(component, :zoom, zoom)
end

The typed wrappers below cover the queries and the camera math, check their arguments and describe their answers. This reaches everything else, such as the getters in the table under "Answers".

Options

  • :reply - required. The action that receives the answer, in any shape an event prop takes (see HoloMap.Event): an action name, which goes to the page, or %{action: ..., target: ..., params: ...}. The params are merged under the answer, as an event's are.
  • :source - a source id. The method is called on that source, as map.getSource(source) returns it, rather than on the map.
  • :limit - for a method that finds features, the most features the answer carries. A positive integer; defaults to 100.
  • :geometry - for a method that finds features, false leaves each feature's geometry out, which keeps the answer small. Defaults to true.

Any other option raises ArgumentError, and so do a missing :reply, a :limit that is not a positive integer and a :geometry that is not a boolean.

The request crosses into the browser as JSON, so args may hold lists, maps, strings, numbers, booleans and nil, and atoms, which arrive as strings. A tuple raises ArgumentError: give coordinates as lists here, or use a typed wrapper, which takes tuples.

Answers

The reply's params hold one of two keys, never both:

  • :result - the answer, as plain data. MapLibre's LngLat becomes [lng, lat], its Point [x, y] and its LngLatBounds [[west, south], [east, north]], as in event payloads. A missing answer is nil, as is a number that is not finite. Object keys arrive as atoms, as Hologram gives every action's params.
  • :error - %{message: message} when the call throws, when MapLibre reports an error while it answers (such as a query for a layer the style lacks, which the map's on_error hears as well), when a promise the method returns rejects, when the answer holds something that is not plain data (such as a DOM element), or when the map is not there to answer: it did not boot within five seconds, MapLibre could not build it, or HoloMap.Runtime.destroy/1 tore it down. Also when the map has no style to answer from: MapLibre could not load a style it built from scratch, or its first.

A method that finds features, queryRenderedFeatures or querySourceFeatures, or with :source a clustered GeoJSON source's getClusterLeaves or getClusterChildren, answers with a list of features as layer events carry them (id, source, source_layer, properties, geometry), at most :limit of them, and with truncated: true when it left any out. getClusterLeaves(cluster_id, limit, offset) takes its limit from :limit, in place of the one in args, and its offset from args; get_cluster_leaves/4 sends both. A source that is not clustered answers those two with an :error. A method that returns a promise is answered when the promise settles.

Method:result
"getCenter"[lng, lat]
"getZoom"a number
"getBounds"[[west, south], [east, north]]
"getStyle"the style, as MapLibre serialises it, including inline GeoJSON data
"getStyleUrl"the URL of the style, or nil for a style given as a map
"getLayersOrder"layer ids, bottom to top
"listImages"image ids
"areTilesLoaded"a boolean
"getGlobalState"a map
"calculateAnchoredCameraOptions"%{center: [lng, lat], zoom: zoom}
"getRoll" / "getCenterElevation" / "getVerticalFieldOfView"a number: degrees, metres above sea level, degrees
"getPadding"%{top: t, bottom: b, left: l, right: r}, in pixels
"getCenterClampedToGround"a boolean

To tell apart the answers to several requests that reply to one action, give each its own params:

HoloMap.API.request("explorer", "getZoom", [],
  reply: %{action: :read, params: %{ref: "zoom"}}
)

The params travel as JSON, as an event prop's do, so an atom among their values comes back as a string. :result, :error and :truncated win over params of the same name.

When it is answered

A request waits, as a call does, for a map that has not booted yet and for a style that is loading, and is answered after the calls made before it. A style that fails to load and leaves the map with no style answers it with an :error, as it answers every request made until the map is asked for another style (see HoloMap.Map's Changing the style). The answer reaches the page only while the map's container is on it: once a navigation has taken the page away, nobody is waiting for it, and it is dropped.

setStyle is refused with an :error; use set_style/3. A method that changes the map rather than answering belongs in HoloMap.Runtime.call/3.

reset_north(cid, opts \\ [])

@spec reset_north(
  String.t(),
  keyword()
) :: :ok

Rotates the map back to north up, over a second unless :duration says otherwise. Takes the options zoom_in/2 takes.

reset_north_pitch(cid, opts \\ [])

@spec reset_north_pitch(
  String.t(),
  keyword()
) :: :ok

Rotates the map back to north up and levels it: bearing, pitch and roll back to 0, over a second unless :duration says otherwise. Takes the options zoom_in/2 takes.

resize(cid)

@spec resize(String.t()) :: :ok

Recomputes the map's size after its container has been resized.

Almost never needed. MapLibre observes its own container, so a map whose container changes size follows along by itself and calling this does nothing. That holds for CSS transitions, flex reflows and window resizes alike.

The one case where it is required is a map built with track_resize={false}, which switches that observer off. The canvas then keeps its old size until this is called:

<HoloMap.Map cid="panel" style={@style} width={@width} track_resize={false} />

def action(:panel_resized, _params, component) do
  HoloMap.API.resize("panel")
  component
end

rotate_to(cid, bearing, opts \\ [])

@spec rotate_to(String.t(), number(), keyword()) :: :ok

Rotates the map to a bearing, with an animated move.

HoloMap.API.rotate_to("explorer", 90)

A bearing of 90 puts east up. Takes the options of ease_to/2 that shape the move, except :bearing, which bearing is. Any other option raises ArgumentError, as does a bearing that is not a number.

set_center_clamped_to_ground(cid, clamped)

@spec set_center_clamped_to_ground(String.t(), boolean()) :: :ok

Says whether MapLibre keeps the map's centre on the ground.

true, MapLibre's default, sets the centre's elevation to the terrain's under it, or to 0 without terrain, as the camera moves. false leaves it at sea level, or where set_center_elevation/2 put it, which keeps the camera above the ground when the pitch passes 90 degrees. Nothing moves until the camera does.

HoloMap.API.set_center_clamped_to_ground("alps", false)

set_center_elevation(cid, elevation)

@spec set_center_elevation(String.t(), number()) :: :ok

Sets the elevation of the map's centre, in metres above sea level, with no animation, as jump_to/2 with :elevation does.

Over terrain, MapLibre puts the centre back on the ground on the next move while set_center_clamped_to_ground/2 leaves it clamped, as a map is unless told otherwise.

HoloMap.API.set_center_elevation("alps", 4_478)

set_feature_state(cid, feature, state)

@spec set_feature_state(String.t(), map(), map()) :: :ok

Attaches feature state, the mechanism behind hover and selection styling.

feature identifies the feature: %{source: "parcels", id: 12}, plus :source_layer for a vector source.

HoloMap.API.set_feature_state("explorer", %{source: "parcels", id: id}, %{hover: true})

set_filter(cid, layer_id, filter)

@spec set_filter(String.t(), String.t(), list() | nil) :: :ok

Sets a layer's filter, or clears it when filter is nil.

HoloMap.API.set_filter("explorer", "parcels-fill", ["==", ["get", "zone"], "R1"])

set_layout_property(cid, layer_id, property, value)

@spec set_layout_property(String.t(), String.t(), atom() | String.t(), term()) :: :ok

Sets one layout property on a layer.

Useful for toggling visibility without removing the layer:

HoloMap.API.set_layout_property("explorer", "parcels-fill", :visibility, "none")

set_padding(cid, padding)

@spec set_padding(String.t(), map() | keyword()) :: :ok

Sets the padding around the viewport, in pixels, with no animation.

padding is a map, or a keyword list, of any of :top, :bottom, :left and :right. A side left out keeps the padding it has. The padding moves the point the camera centres on, and the vanishing point, to the middle of what it leaves, so a side panel over the map does not hide the centre:

HoloMap.API.set_padding("explorer", %{left: 320})

The camera moves at once, and the move is reported to the map's move events, as a user's is. A padding that is not a map of those sides to numbers raises ArgumentError.

set_paint_property(cid, layer_id, property, value)

@spec set_paint_property(String.t(), String.t(), atom() | String.t(), term()) :: :ok

Sets one paint property on a layer.

property may be given as an atom in Elixir style (:fill_color) or as the specification name ("fill-color").

set_roll(cid, roll)

@spec set_roll(String.t(), number()) :: :ok

Sets the camera's roll, in degrees, with no animation: its turn about the line it looks along. jump_to/2 with :roll does the same, and fly_to/2 and ease_to/2 animate it.

HoloMap.API.set_roll("explorer", 15)

set_style(cid, style, opts \\ [])

@spec set_style(String.t(), String.t() | map(), keyword()) :: :ok

Replaces the whole style.

Prefer HoloMap.Map's style prop. Either way MapLibre diffs the new style against the one on the map, and the sources, layers, images, sprites, terrain, sky and light the components declared stay on the map, so only the basemap changes. The components' layers keep their template order and go back to their props, losing what HoloMap.API set on them. HoloMap.Map's Changing the style describes what is kept, and when MapLibre builds the new style from scratch instead. Calls made while the new style loads wait for it. A style MapLibre cannot load ends the wait, and the same section says what the map is left with. On a map left with no style, the call asks for the new style at once.

HoloMap.API.set_style("explorer", "https://tiles.example.com/dark.json")

Options

  • :diff - false asks MapLibre to build the new style from scratch: the map starts from an empty style, and the reconciler declares the sources, layers, images, sprites, terrain, sky and light it owns again once the new style has loaded. Their feature state is cleared. Defaults to true.

Any other option, or a :diff that is not a boolean, raises ArgumentError.

set_vertical_field_of_view(cid, fov)

@spec set_vertical_field_of_view(String.t(), number()) :: :ok

Sets the camera's vertical field of view, in degrees, with no animation.

MapLibre's default is about 36.87 degrees. A wider one shows more of the ground ahead on a pitched map, and draws it more distorted. MapLibre keeps it between 0.1 and 150 degrees, and a value outside is set to the nearer end. The change is reported to the map's move events, unless the field of view was the one given already. A number is all it takes: anything else raises ArgumentError.

HoloMap.API.set_vertical_field_of_view("explorer", 30)

snap_to_north(cid, opts \\ [])

@spec snap_to_north(
  String.t(),
  keyword()
) :: :ok

Rotates the map back to north up when its bearing is already close to it, within HoloMap.Map's bearing_snap, 7 degrees unless set, and leaves it as it is otherwise. Takes the options zoom_in/2 takes.

stop(cid)

@spec stop(String.t()) :: :ok

Stops the camera move in progress where it is.

The move ends as any move does, and reports its end events, on_move_end among them. A map that is not moving stays as it is.

HoloMap.API.stop("explorer")

trigger_geolocate(cid)

@spec trigger_geolocate(String.t()) :: :ok

Asks for the user's position, as a click on the map's HoloMap.Control.Geolocate button does.

def action(:locate_me, _params, component) do
  HoloMap.API.trigger_geolocate("explorer")
  component
end

The answer arrives as the control's events: on_geolocate with the position, or on_error. The browser asks the user for permission the first time, as it does for a click. With track_user_location, the call toggles following the user, as the button does: it starts following, stops when it already follows, and brings the camera back to the user when a move made it stop.

The control is found by kind. A map with no HoloMap.Control.Geolocate logs a console warning and nothing happens. A map with several triggers the first declared in the template, and logs a console warning, once per map, naming that control's corner.

Like the other calls, it waits for the map to boot and for a style to load. MapLibre sets the control up once the browser has said whether it supports geolocation, and a trigger before then is tried again on each animation frame for about a second, then dropped with a console warning.

unproject(cid, point, opts)

@spec unproject(String.t(), {number(), number()} | [number()], keyword()) :: :ok

Finds the coordinate at a pixel position, and dispatches it to an action.

point is an {x, y} pixel position relative to the map's container, as an event's point is. The answer's :result is [lng, lat]. Takes only :reply.

HoloMap.API.unproject("explorer", {400, 300}, reply: :point_resolved)

update_geojson(cid, source_id, diff)

@spec update_geojson(String.t(), String.t(), keyword()) :: :ok

Changes some features of a HoloMap.Source.GeoJSON, without changing its data prop.

For an application that already knows what changed, such as a feed that sends the vehicles that moved, this hands MapLibre's updateData the change alone, and MapLibre loads again only the tiles it touches:

HoloMap.API.update_geojson("fleet-map", "fleet",
  add: [feature],
  update: [%{id: 7, new_geometry: %{type: "Point", coordinates: [-70.1, 19.2]}}],
  remove: [3]
)

source_id is the id of a HoloMap.Source.GeoJSON on the map. The diff names features by id: the property the source's promote_id names, or the feature's own id without one.

Diff

  • :remove_all - true removes every feature first.
  • :remove - the ids of the features to remove.
  • :add - GeoJSON features to add. One whose id the source holds replaces that feature.
  • :update - a map for each feature to change, with its :id and any of :new_geometry, a GeoJSON geometry; :remove_properties, a list of property names to take away; :add_or_update_properties, a map of the properties to set; and :remove_all_properties, true to take every property away before those are set.

MapLibre applies them in that order, and skips an id the source lacks. An id is an integer or a string. A key the diff does not take, or a value of the wrong kind, raises ArgumentError.

What the source holds

The source keeps the change until its data prop changes. A render that leaves data as it was, a style change, a style built from scratch, a source rebuilt for another prop and a lost WebGL context all keep it. The next change to data wins: afterwards the source holds exactly the new data, and the features this call changed are gone unless data has them. With incremental, the browser runtime sends that change as a diff from what the source holds, this call's changes included; without it, data is set whole.

A change to data means a render whose data differs from the previous render's, not from what the source holds: rendering the same data again keeps this call's changes. The call and the renders take effect in the order the browser receives them. While the map waits for a style, or for a lost WebGL context to come back, they wait in that order too, so a data change rendered after the call still wins, and the call applies to the data the source held before that change.

MapLibre needs ids it can tell the features apart by, so the call changes nothing and logs a console warning for a source the map lacks or whose id the style took over, a source whose data is not a FeatureCollection given inline (a URL, say), one with generate_id, whose ids MapLibre's worker numbers itself, one with a feature that has no id or shares one, and a diff that adds a feature without an id. Like the other calls, it waits for the map to boot and for a style to load.

zoom_in(cid, opts \\ [])

@spec zoom_in(
  String.t(),
  keyword()
) :: :ok

Zooms in by one level, with an animated move.

Takes the options of an animation: :duration, :easing, :offset, :animate, :essential and :freeze_elevation, as fly_to/2 documents them. Any other option raises ArgumentError. On a map with a zoom_snap (see HoloMap.Map), it lands on a multiple of it.

HoloMap.API.zoom_in("explorer", duration: 300)

zoom_out(cid, opts \\ [])

@spec zoom_out(
  String.t(),
  keyword()
) :: :ok

Zooms out by one level, with an animated move. Takes the options zoom_in/2 takes.

zoom_to(cid, zoom, opts \\ [])

@spec zoom_to(String.t(), number(), keyword()) :: :ok

Zooms the map to a zoom level, with an animated move.

HoloMap.API.zoom_to("explorer", 12, around: {-70.66, 19.45})

:around keeps a coordinate where it is on screen while the camera zooms about it. Takes the options of ease_to/2 that shape the move, except :zoom, which zoom is. Any other option raises ArgumentError, as does a zoom that is not a number.