LiveMap
A Phoenix LiveView
Component for displaying an interactive map with dynamic data.
The library requires Elixir 1.16+, Phoenix 1.8+, and Phoenix LiveView 1.1+.
By rendering the map on the server, it avoids the client-side map libraries
for simple mapping needs. Utilizing LiveView, we can also update map data on
the server, and let the browser do what it does best—rendering markup.
The map is rendered as an SVG. Raster and standalone SVG sources are emitted as
<image> tiles, while Shortbread-compatible vector sources are fetched and
decoded on the server into nested SVG tiles. LiveMap progressively injects
standalone SVG tiles so page-level CSS can style them; the external image
remains the no-JavaScript fallback.
Please consult and follow usage policies
of the tile servers.
Usage
A LiveMap can be added to a LiveView by:
<.live_component
module={LiveMap} id="live-map"
title="Example Live Map"
width="800" height="600"
center="10.4197639,107.1070841" zoom="11"
rendering-type="vector"
>
<%# Styles slot %>
<:style>
/* CSS custom variables or class selectors to customize map colors */
:root {
--live-map-water-fill: #38bdf8;
--live-map-land-fill: #fef08a;
}
.live-map-shortbread-role-building {
fill: #cbd5e1;
}
</:style>
<%# Optional custom HTML map controls %>
<:map_control action="pan-up">
<span class="inline-flex h-6 w-6 items-center justify-center rounded bg-white text-slate-900">↑</span>
</:map_control>
<:map_control action="zoom-in">
<span class="inline-flex h-6 w-6 items-center justify-center rounded bg-white text-slate-900">+</span>
</:map_control>
<:map_control action="zoom-out">
<span class="inline-flex h-6 w-6 items-center justify-center rounded bg-white text-slate-900">-</span>
</:map_control>
<:map_control action="fullscreen">
<span class="inline-flex h-6 w-6 items-center justify-center text-slate-900">⛶</span>
</:map_control>
<%# Optional SVG overlays projected from map coordinates %>
<:polygon
id="district"
label="Sample district"
points={[
%{latitude: 10.34, longitude: 107.07},
%{latitude: 10.35, longitude: 107.09},
%{latitude: 10.33, longitude: 107.11}
]}
/>
<:polyline
id="route"
label="Sample route"
points={[
%{latitude: 10.34, longitude: 107.07},
%{latitude: 10.36, longitude: 107.10},
%{latitude: 10.38, longitude: 107.13}
]}
/>
<%# A single explicit marker %>
<:marker
id="harbor"
position="10.411379,107.136224"
title="Harbor"
/>
<%# Add a slot body to <:marker> when you want custom HTML marker UI. %>
<%# Multiple markers via :for %>
<:marker
:for={marker <- @visible_markers}
id={marker.id}
position={{marker.latitude, marker.longitude}}
title={marker.label}
/>
</.live_component>
Run examples/live_maps.exs for a single-file LiveView example powered by Mix.install/1.
Map controls are opt-in: LiveMap renders no navigation buttons by default. Add
repeated :map_control slots with an action and HTML content to enable any
combination of zoom-in, zoom-out, pan-up, pan-right, pan-down,
pan-left, and fullscreen. Pan controls initially render as a compact D-pad
launcher. Activating it reveals the directional controls, with zoom in above
the right control and zoom out below it. The optional positive step defaults
to 1. A zoom step changes one zoom level; a pan step moves half the map width
or height at the current zoom.
The fullscreen action toggles a server-rendered, CSS viewport-filling mode and
does not require a custom JavaScript hook. Browser-native fullscreen, which also
hides browser chrome, requires the client-side Fullscreen API and is therefore
outside LiveMap's server-rendered controls.
Use on_bounds_changed when the parent LiveView needs to retain or persist
control-driven bounds changes. The server callback receives the map id, triggering
action, new center, and new zoom; it can send that value back to the parent
process for URL patching or other state updates.
Each :marker slot entry must provide position and title. The
optional id is used to generate a stable DOM id. LiveMap only projects and renders
the markers it receives; deciding which markers to pass remains the responsibility of
the parent LiveView. When the :marker slot body is omitted, LiveMap renders a
default SVG marker pin with the marker title exposed through the SVG title. If a body is provided, it must be HTML content;
LiveMap wraps it in a <foreignObject> automatically. This keeps the public API
decoupled from the internal SVG rendering details while still allowing rich HTML
marker UIs. No :let or projected slot assigns are required. You can pass a single
marker directly, or emit multiple marker slots with :for.
Like Google's <gmp-map>
and <gmp-advanced-marker>
elements, center and position accept a "latitude,longitude" string.
Elixir callers may also pass a
{latitude, longitude} tuple or %{lat: latitude, lng: longitude} map.
The map-level latitude and longitude attributes and the marker-level
latitude, longitude, and label attributes are deprecated compatibility
fallbacks. When both forms are supplied, center, position, and title win.
Custom map controls use HTML content only. LiveMap wraps that content for
display inside the SVG control chrome. The old :zoom_in and :zoom_out slots
remain as deprecated one-step aliases for the corresponding map-control actions.
Polygon and polyline overlays are projected in map coordinates and rendered as
SVG shapes on their own layer. Each :polygon or :polyline slot accepts a
points list of %{latitude: ..., longitude: ...} maps, with optional id
and label attributes. LiveMap renders default SVG <polygon> and <polyline>
elements for these overlays. It drops each point that is less than half a pixel
from the point before it at the zoom of the map (the last point stays): a long
line at a low zoom has many such points, and they change nothing on the screen.
A :polygon can have holes: holes is a list of rings, each a list of points
as points. LiveMap renders a polygon with holes as a <path> with
fill-rule="evenodd", one subpath for each ring. The holes move with the
points to the copy of the world of the map. A hole with fewer than three
points (after the half-pixel rule above) has no area, and is not in the path.
<:polygon
id="lake"
points={shore}
holes={[island]}
class="fill-sky-500/30"
/>
A :polygon or a :polyline can have a group. The consecutive shapes with
the same group are in one <g class="live-map-group" data-live-map-group="...">.
Give the group an opacity in CSS, and its shapes become one layer: two shapes
that overlap do not make the overlap darker, and shapes that touch show no
light line on their edge. LiveView also tracks the shapes of a group apart from
the other shapes: a new shape in a group does not move the other shapes in the
list, so they are not sent again.
<:polygon :for={tile <- @tiles} id={tile.id} points={tile.points} group="fog" />
[data-live-map-group="fog"] { opacity: 0.45; }
HTML marker example:
<:marker id="harbor" position="10.411379,107.136224" title="Harbor">
<button class="rounded-full bg-emerald-700 px-3 py-1 text-xs font-semibold text-white">
Harbor
</button>
</:marker>
Moving the map
Each layer of the map (the background tiles, the tiles, the shapes and the
markers) is in a group with the class live-map-layer. The tiles, the
points of the shapes and the markers have their place from a fixed origin,
and a CSS transform on the group moves the layer to the view. The origin
is the corner of a cell of 220 pixels: up to zoom 12 it is the
corner of the world, and at higher zooms the numbers stay small enough for
the floats of a browser.
So a new center at the same zoom changes only the transform of the
groups, while the center stays in the same cell. The markers and the points
of the shapes do not change, and LiveView sends only the new transform. A
map that follows a moving point, or a map that a hook pans, sends a small
update for each move, not all of the points of its lines again. When new
tiles come into the view, LiveView sends only the new tiles: each tile has
a key from its place in the lists of the tiles (:key), and an id from
its zoom and its place, so the browser keeps the tiles that stay in the
view, with their images.
The id of each group has the zoom and the cell of the origin
(MAP_ID-tile-layer-ZOOM-X-Y). A new zoom or a new cell gives new groups.
This lets an app animate a move of the map with CSS only, with no
animation of a zoom:
#trip-map .live-map-layer {
transition: transform 250ms linear;
}
Animate the markers that move too (.live-map-marker has a CSS transform
for its place), with the same time, so that they move with the map.
Rendering Type and Tile Sources
Set rendering-type to the raster|vector enum to select LiveMap's built-in
OpenStreetMap raster or Shortbread vector source. LiveMap keeps raster as the
default for backward compatibility:
<.live_component
module={LiveMap}
id="live-map"
center="10.4197639,107.1070841"
zoom={11}
rendering-type="raster"
/>
Use rendering-type="vector" to switch to the built-in OSM vector source
without configuring tile_source. The optional Req dependency is required for
vector rendering.
tile_source remains supported for backward compatibility and custom tile
servers. If both attributes are supplied, rendering-type selects the built-in
source.
Tile source type is inferred from the URL by default: .mvt, .pbf and
.pmtiles URLs are treated as MVT sources, .svg URLs are treated as
standalone SVG sources, and everything else is treated as raster.
Raster and Shortbread MVT sources support overzoom above their max_zoom by
cropping the appropriate parent tile. Shortbread MVT sources are
server-rendered:
<.live_component
module={LiveMap}
id="live-map"
center="10.4197639,107.1070841"
zoom={15}
tile_source={%{
url: "https://vector.openstreetmap.org/$VERSION/{zoom}/{x}/{y}.mvt",
version: "shortbread_v1",
max_zoom: 14,
headers: [{"x-example-header", "demo"}]
}}
/>
Standalone SVG tile sources
Point tile_source at a display-ready SVG tile endpoint to keep tile bytes out
of LiveView diffs:
<.live_component
module={LiveMap}
id="svg-map"
center="10.4197639,107.1070841"
zoom={11}
base-style="detailed"
styles={@map_styles}
tile_source={%{
url: "/vector/{zoom}/{x}/{y}.svg",
attribution: "© OpenStreetMap contributors"
}}
/>
Do not also set rendering-type: when present, it intentionally selects one of
LiveMap's built-in sources instead of tile_source. Root-relative URLs are
accepted for raster and SVG browser-loaded tiles. Server-fetched MVT sources
must remain absolute HTTP(S) URLs.
LiveMap's built-in runtime colocated hook puts the SVG of each tile into the
page. It uses the Cache API of the browser according to the HTTP freshness
headers, and scopes the SVG IDs. No asset import or custom hook setup is
necessary.
The browser downloads each tile one time:
- The first render of the page (for a browser with no JavaScript yet) shows
each tile as an
<image>. The hook waits for this image, then takes the
same response from the HTTP cache.
- The tiles of a later render (over the socket) have no
<image>. The hook
downloads them.
Give the SVG tiles an HTTP cache lifetime (Cache-Control with max-age):
with no-store, the hook downloads a tile of the first render a second
time. With no JavaScript, each tile stays an image. When the hook cannot put
a tile into the page (a request that failed, an SVG that is not valid), the
tile shows as an image.