HoloMap.API (HoloMap v0.3.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 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
Locate the user from an actiontrigger_geolocate/1

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 or pitch changes, which sets only the values that changed. 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.

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

Zooms in to where a cluster breaks apart.

Fits the camera to a bounding box.

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.

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.

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

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 one paint property on a layer.

Replaces the whole style.

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.

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.
  • :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.

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 same options as fly_to/2 minus the flight-specific :speed and :curve, which it ignores.

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.

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)

fly_to(cid, opts)

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

Animates the camera along a curved flight path.

Accepts :center, :zoom, :bearing, :pitch, :duration, :easing, :speed, :curve, :offset, :padding, :max_duration, :essential and :animate.

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

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.

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.

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}

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. 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.

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

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_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_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.

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.

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)