Skip to content

Live fleet

Sample data

Sample vans and trucks that report their positions from the server and move between reports, with trails behind them, the trucks pushed to their layer alone, and any of them to follow with the camera.

Click a van or a truck to follow it.

Reports

interval

Follow a vehicle

Sample data: made-up vans and trucks going round made-up loops around Valencia, faster than city traffic, in straight lines between the corners of each loop.

The vans are markers. The trucks are the points of one layer, which takes only their new positions from the server. The map follows either: a van by its marker's id, a truck by the layer's id and the truck's. Visitors who ask for less motion see the vehicles, and the map that follows one, jump from one report to the next.

@interval
2000
@playing
true
@reports
0
@followed
nil
@follow_ended
nil
lib/maplibrex_demo_web/scenarios/fleet_scenario.html.heex
<div id="fleet-scenario">
  <.example_frame error={@map_error} error_id="scenario-fleet-map-error" tall>
    <%!-- follow: what the camera keeps at the centre as it moves: the id of
          a van's marker, or a truck as {layer_id, feature_id}. Zooming and
          turning the map keep following, dragging it ends it, and the map
          pushes map:follow_ended. map:loaded starts the reports. --%>
    <.map
      id="scenario-fleet-map"
      center={Fleet.centre()}
      zoom={13.2}
      style={basemap(@theme)}
      follow={follow_target(@followed)}
      attribution_control={false}
      events={["map:loaded", "map:follow_ended", "map:error"]}
      class="h-full w-full"
    />

    <%!-- Whether the map follows a vehicle, over the map. --%>
    <p
      id="scenario-fleet-following"
      data-following={to_string(@followed != nil)}
      role="status"
      class="absolute top-3 left-3 flex items-center gap-1.5 rounded-ui border border-line bg-canvas px-2.5 py-1.5 text-ui shadow-overlay"
    >
      <%= if @followed do %>
        <.icon name="hero-viewfinder-circle-mini" class="size-4 shrink-0 text-accent-ink" />
        <span>
          {gettext("Following %{vehicle}. Drag the map to stop.", vehicle: @followed)}
        </span>
      <% else %>
        <.icon name="hero-cursor-arrow-rays-mini" class="size-4 shrink-0 text-ink-subtle" />
        <span class="text-ink-muted">{gettext("Click a van or a truck to follow it.")}</span>
      <% end %>
    </p>
  </.example_frame>

  <.navigation_control id="scenario-fleet-navigation" map_id="scenario-fleet-map" />

  <%!-- The attribution, under the zoom buttons: at phone width MapLibre's
        own opens across the bottom of the map, over the legend. --%>
  <.attribution_control
    id="scenario-fleet-attribution"
    map_id="scenario-fleet-map"
    position="top-right"
  />

  <%!-- The trucks: one symbol layer, its data assigned once. Each report
        pushes their new positions (layer:update_data); every truck has an
        id, its vehicle_id, so the layer moves it there over the interval
        and turns its heading, which icon-rotate reads, with it.
        A click on a truck pushes layer:feature_clicked, within 10 px of its
        small icon (hit_width), and the map follows it. The truck followed
        has the feature state followed, which its colour reads. --%>
  <.image
    id="scenario-fleet-truck"
    map_id="scenario-fleet-map"
    url="/images/vehicle.svg"
    width={24}
    height={24}
    sdf
    pixel_ratio={2}
  />

  <.geojson_layer
    id="scenario-fleet-trucks"
    map_id="scenario-fleet-map"
    type="symbol"
    data={@trucks}
    promote_id="vehicle_id"
    transition={@interval}
    transition_heading="heading"
    transition_max_distance={max_move()}
    layout={
      %{
        "icon-image" => "scenario-fleet-truck",
        "icon-rotate" => ["get", "heading"],
        "icon-rotation-alignment" => "map",
        "icon-allow-overlap" => true
      }
    }
    paint={truck_paint(@theme)}
    feature_state={followed_truck(@followed)}
    events={["layer:feature_clicked"]}
    cursor="pointer"
    hit_width={10}
  />

  <%!-- One trail for every truck of the layer, under the icons. --%>
  <.trail
    id="scenario-fleet-truck-trails"
    map_id="scenario-fleet-map"
    layer="scenario-fleet-trucks"
    before_id="scenario-fleet-trucks"
    max_points={30}
    max_distance={max_move()}
    paint={truck_trail_paint()}
  />

  <%!-- The vans: markers drawn as an arrow, turned to their heading, which
        move there over the interval. A click on one pushes marker:clicked,
        and the map follows it. --%>
  <.marker
    :for={van <- @vans}
    id={"scenario-fleet-#{van.id}"}
    map_id="scenario-fleet-map"
    lng_lat={van.lng_lat}
    rotation={van.heading}
    transition={@interval}
    transition_max_distance={max_move()}
    events={["marker:clicked"]}
  >
    <span
      id={"scenario-fleet-#{van.id}-icon"}
      data-followed={@followed == van.id}
      title={van.id}
      class={[
        "grid size-9 cursor-pointer place-items-center rounded-full",
        @followed == van.id && "bg-white/85 ring-2 ring-[#7c5cd6]"
      ]}
    >
      <.vehicle_icon color={palette(:van)} />
    </span>
  </.marker>

  <%!-- A trail for each van, fading towards its tail: the last two
        minutes of its path, kept in the browser. --%>
  <.trail
    :for={van <- @vans}
    id={"scenario-fleet-#{van.id}-trail"}
    map_id="scenario-fleet-map"
    marker={"scenario-fleet-#{van.id}"}
    max_age={120}
    max_distance={max_move()}
    paint={
      %{
        "line-width" => 3,
        "line-gradient" => van_trail_gradient()
      }
    }
    layout={%{"line-cap" => "round", "line-join" => "round"}}
  />

  <%!-- What the map shows, from the fleet's palette. The vehicles' entries
        draw them as the map does; the trucks' and the trails' entries hide
        and show their layers. --%>
  <.legend
    id="scenario-fleet-legend"
    map_id="scenario-fleet-map"
    title={gettext("Fleet")}
    collapsible
  >
    <:item label={gettext("Van, a marker")}>
      <.vehicle_icon color={palette(:van)} class="size-4" />
    </:item>
    <:item label={gettext("Truck, a point of the layer")} layers={["scenario-fleet-trucks"]}>
      <.vehicle_icon color={palette(:truck)} class="size-4" />
    </:item>
    <:item label={gettext("Truck followed")}>
      <.vehicle_icon color={palette(:followed)} class="size-4" />
    </:item>
    <:item
      color={palette(:van)}
      shape={:line}
      label={gettext("Van trails")}
      layers={van_trail_ids(@vans)}
    />
    <:item
      color={palette(:truck)}
      shape={:line}
      label={gettext("Truck trails")}
      layers={["scenario-fleet-truck-trails"]}
    />
  </.legend>

  <div class="grid gap-x-8 gap-y-4 border-t border-line px-4 py-4 lg:grid-cols-[1fr_auto]">
    <div class="flex flex-wrap gap-x-8 gap-y-4">
      <%!-- The server's clock: paused, one report at a time. --%>
      <.example_group id="scenario-fleet-reports" label={gettext("Reports")}>
        <.example_button id="scenario-fleet-play" pressed={@playing} phx-click="play">
          <.icon
            name={if(@playing, do: "hero-pause-mini", else: "hero-play-mini")}
            class="size-4"
          />
          {if(@playing, do: gettext("Pause"), else: gettext("Play"))}
        </.example_button>
        <.example_button id="scenario-fleet-report" phx-click="report" disabled={@playing}>
          {gettext("One report")}
        </.example_button>
      </.example_group>

      <%!-- The time between reports, which is also every move's transition. --%>
      <.example_group id="scenario-fleet-intervals" label="interval" code>
        <.example_button
          :for={ms <- intervals()}
          id={"scenario-fleet-interval-#{ms}"}
          code
          pressed={@interval == ms}
          phx-click="interval"
          phx-value-ms={ms}
        >
          {ms}
        </.example_button>
      </.example_group>
    </div>

    <.example_group id="scenario-fleet-follow" label={gettext("Follow a vehicle")}>
      <.example_button
        :for={id <- vehicle_ids()}
        id={"scenario-fleet-follow-#{id}"}
        code
        pressed={@followed == id}
        phx-click="follow"
        phx-value-vehicle={id}
      >
        {id}
      </.example_button>
      <.example_button id="scenario-fleet-stop" phx-click="stop_following" disabled={!@followed}>
        {gettext("Stop following")}
      </.example_button>
    </.example_group>
  </div>

  <div class="space-y-2 px-4 pb-4">
    <.example_note id="scenario-fleet-sample-data">
      {gettext(
        "Sample data: made-up vans and trucks going round made-up loops around Valencia, faster than city traffic, in straight lines between the corners of each loop."
      )}
    </.example_note>
    <.example_note id="scenario-fleet-how" icon="hero-information-circle-micro">
      {gettext(
        "The vans are markers. The trucks are the points of one layer, which takes only their new positions from the server. The map follows either: a van by its marker's id, a truck by the layer's id and the truck's. Visitors who ask for less motion see the vehicles, and the map that follows one, jump from one report to the next."
      )}
    </.example_note>
  </div>

  <%!-- followed is what follow gets; map:follow_ended sets follow_ended. --%>
  <.example_readout values={[
    interval: @interval,
    playing: @playing,
    reports: @reports,
    followed: shown(follow_target(@followed)),
    follow_ended: @follow_ended || "nil"
  ]} />
</div>
lib/maplibrex_demo_web/scenarios/fleet_scenario.ex
defmodule MaplibrexDemoWeb.Scenarios.FleetScenario do
  @moduledoc """
  A live fleet, driven from the server: on the LiveView's clock, a report
  of every vehicle's position every interval, from `MaplibrexDemo.Fleet`,
  a sample fleet that stands in for a real one's reports.

  The vans are markers: each moves and turns to its new position over the
  interval (`transition`) and leaves a trail. The trucks are the points of
  one symbol layer, assigned once, at mount: each report pushes their new
  positions alone (`layer:update_data`), and the layer moves them and turns
  their icons over the interval too, with one trail for all of them.

  A click on a vehicle makes the map follow it (`follow`) until the user
  drags the map (`map:follow_ended`): a van by its marker's id, a truck by
  the layer's id and the truck's own, `{layer_id, vehicle_id}`. The truck
  followed turns orange through its feature state (`feature_state`).

  A legend says what the vans, the trucks and their trails are. The
  fleet's palette is written once: the markers, the layer's paint, the
  trails and the legend's entries all read it.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  alias MaplibrexDemo.Fleet

  # Demo plumbing, not needed in an application: applies the page's locale
  # and keeps @theme on the page's light or dark theme.
  on_mount MaplibrexDemoWeb.Examples.Plumbing

  # OpenFreeMap's basemap for the page's theme: the map's style follows @theme.
  defp basemap("dark"), do: "https://tiles.openfreemap.org/styles/dark"
  defp basemap("light"), do: "https://tiles.openfreemap.org/styles/positron"

  # The truck icon's halo takes the colour of the page's ground.
  defp halo("dark"), do: "#12141b"
  defp halo("light"), do: "#ffffff"

  # How often the fleet reports, in milliseconds. Each move takes the whole
  # interval, so a vehicle reaches a position as the next one arrives.
  @intervals [1000, 2000, 5000]

  # A move longer than this many metres would be a jump, and break the
  # trail: a vehicle that reappears far away does not fly across the map.
  @max_move 1_000

  # The fleet's palette, once: a van, a truck, the truck followed. The
  # vehicles, their trails and the legend all read it.
  @palette %{van: "#7c5cd6", truck: "#0f8b8d", followed: "#d9480f"}

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(seconds: 0, reports: 0, interval: 2000, map_error: nil)
      |> assign(playing: true, loaded: false, clock: nil)
      |> assign(followed: nil, follow_ended: nil)
      |> assign(:vans, Fleet.vans(0))
      # The trucks' full state, once: the reports push only what changed,
      # and this assign never changes, so LiveView never sends it again.
      |> assign(:trucks, feature_collection(Fleet.trucks(0)))

    {:ok, socket}
  end

  # The clock starts once the map has loaded, so that the first push finds
  # the trucks' layer on the map.
  @impl true
  def handle_event("map:loaded", _params, socket) do
    {:noreply, socket |> assign(:loaded, true) |> start_clock()}
  end

  def handle_event("play", _params, socket) do
    if socket.assigns.playing do
      {:noreply, assign(socket, playing: false, clock: nil)}
    else
      {:noreply, socket |> assign(:playing, true) |> start_clock()}
    end
  end

  # Paused: the next report, one at a time.
  def handle_event("report", _params, socket), do: {:noreply, report(socket)}

  # A new interval: the next report comes after it, and every move takes it.
  def handle_event("interval", %{"ms" => ms}, socket) do
    case Enum.find(@intervals, &(Integer.to_string(&1) == ms)) do
      nil ->
        {:noreply, socket}

      interval ->
        socket = assign(socket, :interval, interval)
        {:noreply, if(socket.assigns.clock, do: schedule(socket), else: socket)}
    end
  end

  # A click on a van or a truck, or its button, follows it; dragging the map
  # ends it.
  def handle_event("marker:clicked", %{"markerId" => "scenario-fleet-" <> id}, socket) do
    {:noreply, follow(socket, id)}
  end

  def handle_event("marker:clicked", _params, socket), do: {:noreply, socket}

  # A click on a truck carries its feature, whose vehicle_id is its id in
  # the layer (promote_id).
  def handle_event(
        "layer:feature_clicked",
        %{"layer_id" => "scenario-fleet-trucks", "feature" => feature},
        socket
      ) do
    {:noreply, follow(socket, feature["properties"]["vehicle_id"])}
  end

  def handle_event("layer:feature_clicked", _params, socket), do: {:noreply, socket}

  def handle_event("follow", %{"vehicle" => id}, socket), do: {:noreply, follow(socket, id)}

  def handle_event("stop_following", _params, socket) do
    {:noreply, assign(socket, :followed, nil)}
  end

  # The map stopped following: the user took the map ("user"), or a camera
  # command moved it ("command"). Clearing `follow` lets the next click
  # follow again.
  def handle_event("map:follow_ended", %{"reason" => reason}, socket) do
    {:noreply, assign(socket, followed: nil, follow_ended: reason)}
  end

  def handle_event("map:error", %{"error" => message}, socket) do
    {:noreply, assign(socket, :map_error, message)}
  end

  # A tick of the running clock is a report, and sets the next tick. A tick
  # of a clock paused or reset since carries another ref, and is dropped.
  @impl true
  def handle_info({:tick, clock}, %{assigns: %{clock: clock}} = socket) when clock != nil do
    {:noreply, socket |> report() |> schedule()}
  end

  def handle_info({:tick, _stale}, socket), do: {:noreply, socket}

  # A report: the vans get new positions, rendered as their lng_lat; the
  # trucks' new positions are pushed to their layer, and nothing else.
  defp report(socket) do
    seconds = socket.assigns.seconds + socket.assigns.interval / 1000

    socket
    |> assign(seconds: seconds, reports: socket.assigns.reports + 1)
    |> assign(:vans, Fleet.vans(seconds))
    |> push_event("layer:update_data", %{
      layer_id: "scenario-fleet-trucks",
      update: Enum.map(Fleet.trucks(seconds), &feature/1)
    })
  end

  defp start_clock(%{assigns: %{playing: true, loaded: true, clock: nil}} = socket),
    do: schedule(socket)

  defp start_clock(socket), do: socket

  defp schedule(socket) do
    clock = make_ref()
    Process.send_after(self(), {:tick, clock}, socket.assigns.interval)
    assign(socket, :clock, clock)
  end

  defp follow(socket, id) do
    if van?(id) or truck?(id),
      do: assign(socket, :followed, id),
      else: socket
  end

  defp van?(id), do: Enum.any?(Fleet.vans(0), &(&1.id == id))
  defp truck?(id), do: Enum.any?(Fleet.trucks(0), &(&1.id == id))

  # What `follow` takes: the id of a van's marker, or, for a truck, the id
  # of its layer and the truck's id in it.
  defp follow_target(nil), do: nil

  defp follow_target(id) do
    if truck?(id), do: {"scenario-fleet-trucks", id}, else: "scenario-fleet-#{id}"
  end

  # The truck followed, as feature state: its colour reads `followed`. An
  # empty map when no truck is followed, so the layer takes the state off.
  defp followed_truck(id) do
    if truck?(id), do: %{id => %{followed: true}}, else: %{}
  end

  # A truck is teal, and orange while the map follows it.
  defp truck_paint(theme) do
    followed? = ["boolean", ["feature-state", "followed"], false]

    %{
      "icon-color" => ["case", followed?, @palette.followed, @palette.truck],
      "icon-halo-color" => halo(theme),
      "icon-halo-width" => 1.5
    }
  end

  defp vehicle_ids, do: Enum.map(Fleet.vehicles(0), & &1.id)

  defp palette(name), do: Map.fetch!(@palette, name)

  # The trucks' trail, in their colour; a van's, in its colour, fading
  # towards its tail.
  defp truck_trail_paint do
    %{"line-color" => @palette.truck, "line-width" => 2, "line-opacity" => 0.6}
  end

  defp van_trail_gradient do
    [
      "interpolate",
      ["linear"],
      ["line-progress"],
      0,
      rgba(@palette.van, 0),
      1,
      rgba(@palette.van, 0.9)
    ]
  end

  # "#7c5cd6" and 0.9 as "rgba(124, 92, 214, 0.9)".
  defp rgba("#" <> hex, alpha) do
    [r, g, b] = for <<pair::binary-2 <- hex>>, do: String.to_integer(pair, 16)
    "rgba(#{r}, #{g}, #{b}, #{alpha})"
  end

  defp van_trail_ids(vans), do: Enum.map(vans, &"scenario-fleet-#{&1.id}-trail")

  # A vehicle, its nose to the north: a van's marker, and the swatches of
  # the legend.
  attr :color, :string, required: true
  attr :class, :string, default: "size-6"

  defp vehicle_icon(assigns) do
    ~H"""
    <svg viewBox="0 0 48 48" class={@class} style={"color: #{@color}"} aria-hidden="true">
      <path
        d="M24 4 39 42 24 34 9 42Z"
        fill="currentColor"
        stroke="#ffffff"
        stroke-width="3"
        stroke-linejoin="round"
      />
    </svg>
    """
  end

  # Each truck is a feature whose `vehicle_id` the layer takes as its id
  # (promote_id), so that a push, a move and a trail all find it by that.
  defp feature_collection(trucks) do
    %{type: "FeatureCollection", features: Enum.map(trucks, &feature/1)}
  end

  defp feature(truck) do
    %{
      type: "Feature",
      geometry: %{type: "Point", coordinates: truck.lng_lat},
      properties: %{vehicle_id: truck.id, heading: truck.heading}
    }
  end

  # The readout shows `follow` as the map gets it.
  defp shown(nil), do: "nil"
  defp shown(marker_id) when is_binary(marker_id), do: marker_id
  defp shown(feature), do: inspect(feature)

  defp intervals, do: @intervals
  defp max_move, do: @max_move
end