HoloMap needs three things from the application that uses it: the Elixir
dependency, the maplibre-gl npm package, and two static files served at a URL
it can reach. Only the first is automatic.
The reason is structural. Hologram resolves bare import specifiers such as "maplibre-gl"
against the host application's assets/package.json, and its compiler
npm-installs only its own. A library has no way to reach into either.
Prerequisites
Hologram 0.12 sets the floor, and it is a high one:
| Minimum | |
|---|---|
| Elixir | 1.19 |
| OTP | 28.1 |
| Node.js | 20 |
| A working Phoenix application | any |
With asdf:
$ asdf install erlang 28.5
$ asdf install elixir 1.19.5-otp-28
Live reload also needs a filesystem watcher. On Linux that is inotify-tools,
and without it mix holo dies at startup with a MatchError on :ignore:
$ sudo apt install inotify-tools # Debian/Ubuntu
1. Add the dependency
def deps do
[
{:hologram, "~> 0.12.11"},
{:holo_map, "~> 0.4"}
]
endHoloMap supports Hologram 0.12.11, the version it is tested on, and later 0.12
releases. Hologram is not yet at 1.0, and a minor release can change behaviour
the library depends on, as 0.12 did for prop validation and attribute escaping.
The requirement therefore stops below 0.13.
Follow Hologram's own installation guide
for the compiler entry, the router plug and the formatter, all of which belong
to the application that owns the Phoenix endpoint, not to HoloMap. Hologram
0.12 serves its bundles from its router, so the guide no longer has a static
path step. An application set up with Hologram 0.11's guide can remove
"hologram" from its endpoint's Plug.Static only: list, as
Serving the bundles explains.
2. Install MapLibre
$ npm install --prefix assets maplibre-gl@^6.19.0
HoloMap is written against MapLibre GL JS 6.19.0, the lowest release this
requirement accepts, and its browser suites run on 6.19.0 and 6.20.0. A later
6.x release also satisfies the requirement.
Add it to a setup alias so a fresh checkout does not silently skip it:
defp aliases do
[
setup: ["deps.get", "assets.install", "compile", "assets.copy"],
"assets.install": &install_npm_deps/1,
"assets.copy": ©_static_assets/1
]
end
defp install_npm_deps(_args) do
{_output, 0} = System.cmd("npm", ["install", "--prefix", "assets"], into: IO.stream())
end3. Serve MapLibre's worker
This step is not optional.
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. What you see is a map that renders its background
and never draws a single tile. MapLibre reports the failed worker through the
map's error event: on_error receives it with the message "Worker failed to
load. Check that the worker URL is correct.", and a map without on_error logs
it to the browser console. The Events guide describes the
payload.
Copy the worker into your static assets:
defp copy_static_assets(_args) do
dist = "assets/node_modules/maplibre-gl/dist"
File.mkdir_p!("priv/static/assets")
for file <- ~w(maplibre-gl.css maplibre-gl-worker.mjs) do
File.cp!(Path.join(dist, file), Path.join("priv/static/assets", file))
end
endHoloMap.Map defaults worker_url to "/assets/maplibre-gl-worker.mjs",
with 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
URL has since 6.13.0. Upgrading maplibre-gl changes the URL, so no browser or
proxy 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.
If the worker lives elsewhere, set the prop:
<HoloMap.Map cid="explorer" style={@style} worker_url="/static/js/maplibre-gl-worker.mjs" />A URL you set is used as it is, with nothing added, so keeping a stale worker
out of caches is then up to you: put a version or a content hash in the URL,
or serve the file with headers that make browsers revalidate it, as the
ETag and the cache-control: public without a max-age that Plug.Static
sends by default do.
MapLibre keeps one worker URL per page, so set the same worker_url on every
map. A map that asks for another one runs on the page's worker, and HoloMap
logs a warning in the browser console.
MapLibre releases before 6.13.0 split the worker in two: it imports
maplibre-gl-shared.mjs by relative path, so an application pinned to one of
them copies that file too and serves it next to the worker. From 6.13.0 the
worker is self-contained, and maplibre-gl-shared.mjs is an empty file that
MapLibre keeps only so that existing copy steps do not fail.
4. Load the stylesheet
MapLibre's controls, markers and popups are unstyled without it. In your layout:
<link rel="stylesheet" href="/assets/maplibre-gl.css" />Or, if your application has a CSS pipeline, import it there instead:
@import "maplibre-gl/dist/maplibre-gl.css";Trusted Types
A page whose Content Security Policy enforces Trusted Types, with
require-trusted-types-for 'script', has the browser refuse a string where it
would become script or markup, unless a policy the page allows made it. Three
parties on a page with a map reach such places:
- Hologram, which evaluates the code of each page with
new Functionand loads page bundles by setting a script'ssrc. - MapLibre, which starts its workers from a URL, and parses the attribution
of a source with a
DOMParser, to sanitize it. HoloMap's components: a marker's slot markup, which the browser runtime clones withinnerHTML, and a popup'shtmlor slot content and a marker'spopup_html, which MapLibre'ssetHTMLinserts withinnerHTML.
HoloMap.Map's trusted_types_policy covers MapLibre's. The browser runtime
creates a policy of that name for MapLibre, which lets it start a worker only
from the page's own origin, or from the blob: URL MapLibre makes from a
worker on another origin, and hands an attribution on to MapLibre's
sanitizer. Allow the name in the page's policy, and set it on every map:
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types default holo-map<HoloMap.Map cid="explorer" style={@style} trusted_types_policy="holo-map" />Every map, because each page bundle carries its own copy of MapLibre (see
the Registering JavaScript guide), and a
copy without a policy cannot build its map on such a page: MapLibre reports
that it "could not build the map", since the browser refuses its
attribution's markup. The first map of each copy sets the policy (see
HoloMap.Map's "Settings for the whole page"). The browser runtime creates
the policy once per page and hands it to every copy, so the directive needs
no 'allow-duplicates'. A browser without Trusted Types gets no policy, and
needs none.
The rest belongs to the page's default policy, which the application
creates in a script its layout loads before Hologram's: Hologram's code and
page bundles, and the components' markup.
trustedTypes.createPolicy("default", {
// The code Hologram evaluates for each page.
createScript: (code) => code,
// Hologram's page bundles.
createScriptURL: (url) => {
if (new URL(url, location.href).pathname.startsWith("/hologram/")) return url;
throw new TypeError(`Blocked script URL ${url}`);
},
// HoloMap's marker slot markup, popup html and slot content, and popup_html.
createHTML: (html) => html,
});createHTML above passes markup on unchanged, so what HoloMap.Popup and
HoloMap.Marker say about escaping an untrusted value still holds. A page
whose popups use text and popup_text, and whose markers have no slot
content, gives the components' markup nothing to create, and can leave
createHTML out.
Tile servers that want a header or a cookie
A tile server behind authentication needs nothing installed:
HoloMap.Map's request_rules adds headers and credentials to the requests
MapLibre makes, by the start of their URL.
<HoloMap.Map cid="private" style={@style} request_rules={[
%{url_prefix: "https://tiles.example.com/", headers: %{"Authorization" => "Bearer " <> @tile_token}},
%{url_prefix: "https://cdn.example.com/", credentials: "include"}
]} />The first rule whose url_prefix a request's URL starts with applies. The
style's own request goes through the rules, and a change to them applies
from MapLibre's next request. "Request rules" in HoloMap.Map has the
details, and the Registering JavaScript guide
covers what rules cannot say, such as a signature computed for each URL.
The rules are rendered into the page
Every value in request_rules, @tile_token above among them, is written
into the page's HTML, where anyone who can open the page can read it. Put
there only what the browser may hold: a token scoped to reading those
tiles, short-lived, or tied to the user who sees the page. A key that must
stay secret belongs in a proxy on your server that adds it to the
requests, and the map then requests the proxy.
A header on a request to another origin makes the browser send a CORS
preflight first, so the tile server must allow the header in its
Access-Control-Allow-Headers, and allow credentials for "include".
PMTiles archives
A PMTiles archive is a whole tileset in one file, which any static server
that answers HTTP range requests can serve. MapLibre reads it through
PMTiles' protocol, from the pmtiles npm package. HoloMap does not import
that package: Hologram puts every package a page's code imports into the
page's bundle, and fails the build when one is not installed, so an import
in HoloMap would make every application install it. An application that
uses PMTiles installs it and registers the protocol itself, in four steps.
Install the package:
$ npm install --prefix assets pmtiles@^4.5.0Serve its browser build,
dist/pmtiles.js, a plain script that defineswindow.pmtiles, as step 3 serves MapLibre's worker:for file <- ~w(pmtiles.js pmtiles.js.map) do File.cp!(Path.join("assets/node_modules/pmtiles/dist", file), Path.join("priv/static/assets", file)) endLoad it in the layout, before the script that registers your JavaScript (see the Registering JavaScript guide), and register the protocol there:
<script src="/assets/pmtiles.js"></script> <script src="/assets/holo_map_extensions.js"></script> <Runtime />window.HoloMap = window.HoloMap || {}; (window.HoloMap.registry ||= []).push((register) => { register.protocol("pmtiles", new pmtiles.Protocol().tile); });Name the archive with a
pmtiles://URL:<HoloMap.Source.Vector id="zones" url="pmtiles://https://cdn.example.com/zones.pmtiles" />A path on your own server takes three slashes:
pmtiles:///assets/zones.pmtiles.
No page bundle imports the package, so it adds nothing to them: the browser
loads pmtiles.js, 20 KB, 8 KB gzipped, once, and Hologram keeps it
through its navigations. Load it in the layout every map page shares: the
registration script runs once, when the first page loads, and a page loaded
first without pmtiles.js leaves the protocol unregistered for the rest of
the visit.
The server must answer range requests, as Plug.Static does, with the
bytes asked for and status 206. PMTiles reads the first 16 KB of the archive
first, and takes a whole file smaller than that as its answer, which is
what Plug.Static sends for it. A server on another origin must allow
Range requests from the page's origin.
request_rules do not reach the archive: PMTiles reads it with requests of
its own. The Registering JavaScript guide shows
how to send a header with them.
Serving the bundles
MapLibre is a big library, and Hologram builds one bundle per page. A page
that uses HoloMap therefore carries its own copy, around 1.1 MB minified and
0.28 MB gzipped, and five such pages are five distinct downloads, not one cached
download reused five times. That is inherent to Hologram's page-bundle model,
not something this library can avoid.
Hologram 0.12 takes care of most of what that implies. Hologram's router serves
the bundles from Hologram's own build directory, as the gzip copies its compiler
writes next to them, and with cache-control: public, max-age=31536000, immutable, which is safe because every bundle is named by its content hash. The
application needs no Plug.Static or compression step of its own for them.
Hologram 0.11 wrote the bundles to the application's priv/static/hologram and
its installation guide added "hologram" to the endpoint's Plug.Static
only: list. Hologram 0.12 removes that directory when it compiles, so an
application upgrading from 0.11 can remove the entry.
Do not serve sourcemaps in production
esbuild writes a sourcemap beside every bundle, and they are about four times the size of the code, 61 MB across this demo. Only a browser with devtools open requests one, so they cost nothing in normal use and everything the moment someone opens the network tab. Hologram's router serves them along with the bundles, so refuse them in a plug that comes before it in the endpoint, and keep them in development:
plug :reject_sourcemaps
# ...
plug Hologram.Router
defp reject_sourcemaps(conn, _opts) do
if String.ends_with?(conn.request_path, ".map") and
not Application.get_env(:my_app, :serve_sourcemaps, false) do
conn |> send_resp(404, "") |> halt()
else
conn
end
enddemo/lib/demo_web/endpoint.ex has this wired up if you want a reference.
Umbrella projects
npm packages live in an assets directory at the umbrella root, and are
resolved from there for every child app. The child that owns the endpoint takes
the Hologram compiler entry; a child that only defines pages and components
takes the dependency alone.
Checking it worked
defmodule MyAppWeb.MapPage do
use Hologram.Page
route "/map"
layout MyAppWeb.Layout
def init(_params, component, _server) do
put_state(component, :style, "https://demotiles.maplibre.org/style.json")
end
def template do
~HOLO"""
<HoloMap.Map cid="check" style={@style} center={{0.0, 20.0}} zoom={2} height="400px">
<HoloMap.Control.Navigation />
</HoloMap.Map>
"""
end
endYou should get a world map with zoom buttons. If you get a coloured rectangle with no countries in it, step 3 is the one to revisit.
Troubleshooting
| Symptom | Cause |
|---|---|
Background renders, no tiles ever, and "Worker failed to load" in on_error or the console | The worker is not being served at worker_url, see step 3 |
| Nothing at all, container has zero height | height was set to nil without CSS taking over |
A pmtiles:// source draws nothing, and the console warns that no JavaScript has called register.protocol("pmtiles", load) | pmtiles.js, or the script that registers the protocol, does not load before <Runtime />, see PMTiles archives |
| "Server returned no content-length header or content-length exceeding request" from PMTiles | The server sends the whole archive for a range request, see PMTiles archives |
boolean expected, string found from MapLibre | A boolean prop this library does not yet coerce. Pass ={true} explicitly and please report it |
Hologram.CompileError naming a HoloMap component, at build time | A template call site misses a required prop, or gives a prop such as a control's position a literal value the component does not accept. The Hologram compiler checks this in a production build or with HOLOGRAM_START=1 |
Hologram.PropError naming a HoloMap component, as a page renders | The same mistake where the compiler cannot see it: a spread, a dynamic tag, a value computed as the template renders, a component rendered programmatically, or a render in development or test without the compiler |
a HoloMap definition component was rendered outside a <HoloMap.Map> | A source, layer, marker, popup or control is not nested inside a map |
mix holo exits with MatchError on :ignore | The filesystem watcher is missing, see Prerequisites |
Browser cannot reach localhost but curl can | The endpoint is listening on IPv4 only while localhost resolves to ::1 |