Skip to content

trail

Stable

Draws where a moving marker, or each moving point of a GeoJSON layer, has just been, as a line kept in the browser.

The example's template and LiveView, read from the files that run in the preview.

lib/maplibrex_demo_web/examples/trail_example.html.heex
<div id="trail-example">
  <.example_frame error={@map_error} error_id="example-trail-map-error">
    <%!-- map:loaded starts the server's clock, which moves the courier. --%>
    <.map
      id="example-trail-map"
      center={@centre}
      zoom={16}
      style={basemap(@theme)}
      events={["map:loaded", "map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- The courier: a new lng_lat every second, which it takes the second
        to reach, in a straight line. A move longer than
        transition_max_distance metres is a jump. --%>
  <.marker
    id="example-trail-courier"
    map_id="example-trail-map"
    lng_lat={corner(@corner)}
    transition={interval()}
    transition_max_distance={jump()}
  >
    <span class="block size-3.5 rounded-full ring-2 ring-white" style="background-color: #7c5cd6" />
  </.marker>

  <%!-- The trail keeps, in the browser, where the marker has been drawn: the
        LiveView sends the courier's positions only, never the path.
        max_points counts the corners kept, max_age the seconds of the path
        shown, and max_distance breaks the line at a longer step, where the
        courier jumps. --%>
  <.trail
    id="example-trail"
    map_id="example-trail-map"
    marker="example-trail-courier"
    max_points={@max_points}
    max_age={@max_age}
    max_distance={@max_distance}
    paint={paint(@gradient)}
    layout={%{"line-cap" => "round", "line-join" => "round"}}
  />

  <div class="space-y-4 border-t border-line px-4 py-4">
    <div class="grid gap-x-8 gap-y-4 lg:grid-cols-[1fr_auto]">
      <%!-- Assigns: each control changes an assign; the trail follows. --%>
      <.example_group id="example-trail-assigns" label={gettext("Set assigns")}>
        <.form
          for={@options}
          id="example-trail-options"
          phx-change="options"
          class="grid w-full gap-4 sm:max-w-lg sm:grid-cols-[1fr_auto] sm:items-end"
        >
          <.example_range field={@options[:max_points]} label="max_points" min="2" max="50" />
          <.example_checkbox field={@options[:gradient]} label="line-gradient" />
        </.form>

        <div class="flex w-full flex-wrap gap-x-8 gap-y-4 pt-1">
          <.example_group id="example-trail-max-ages" label="max_age" code>
            <.example_button
              :for={seconds <- max_ages()}
              id={"example-trail-max-age-#{shown(seconds)}"}
              code
              pressed={@max_age == seconds}
              phx-click="max_age"
              phx-value-seconds={shown(seconds)}
            >
              {shown(seconds)}
            </.example_button>
          </.example_group>

          <.example_group id="example-trail-max-distances" label="max_distance" code>
            <.example_button
              :for={metres <- max_distances()}
              id={"example-trail-max-distance-#{shown(metres)}"}
              code
              pressed={@max_distance == metres}
              phx-click="max_distance"
              phx-value-metres={shown(metres)}
            >
              {shown(metres)}
            </.example_button>
          </.example_group>
        </div>
      </.example_group>

      <%!-- The server's clock: paused, the courier moves a corner at a time. --%>
      <.example_group id="example-trail-drive" label={gettext("Drive the courier")}>
        <.example_button id="example-trail-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="example-trail-step" phx-click="step" disabled={@playing}>
          {gettext("One step")}
        </.example_button>
        <.example_button id="example-trail-jump" phx-click="jump">
          {gettext("Jump across")}
        </.example_button>
      </.example_group>
    </div>

    <.example_note id="example-trail-sample-data">
      {gettext(
        "Sample route: a courier going round twelve corners in the centre of Porto, made up for this example. Visitors who ask for less motion see it jump from corner to corner, and the trail joins the corners."
      )}
    </.example_note>
  </div>

  <.example_readout values={[
    corner: @corner,
    playing: @playing,
    max_points: @max_points,
    max_age: shown(@max_age),
    max_distance: shown(@max_distance),
    gradient: @gradient
  ]} />
</div>
lib/maplibrex_demo_web/examples/trail_example.ex
defmodule MaplibrexDemoWeb.Examples.TrailExample do
  @moduledoc """
  The example of `<.trail>`: a courier, a marker that the server sends to
  the next corner of its round every second and that takes the second to
  get there, with `transition`, and the line of where it has just been,
  which the trail keeps in the browser. `max_points`, `max_age` and
  `max_distance` bound the line and break it where the courier jumps, and a
  `"line-gradient"` fades it towards its tail.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  # Demo plumbing, not needed in an application: applies the page's locale,
  # copies each map event to the page's Events tab 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/liberty"

  @centre [-8.611, 41.1466]

  # Sample route: the twelve corners of a round in the centre of Porto, made
  # up for this example, in metres east and north of @centre.
  @round [
    {0, 180},
    {110, 160},
    {200, 90},
    {230, 0},
    {190, -100},
    {100, -170},
    {0, -190},
    {-120, -160},
    {-210, -80},
    {-230, 20},
    {-180, 110},
    {-90, 170}
  ]

  # Every second the server sends the courier's next corner, and the marker
  # takes that second to get there: `transition` is the interval.
  @interval 1000

  # A move longer than this many metres is a jump. Across the round is
  # longer; from one corner to the next is not.
  @jump 300

  @max_ages [nil, 10, 30]
  @max_distances [nil, @jump]

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(centre: @centre, corner: 0, map_error: nil)
      |> assign(playing: true, loaded: false, clock: nil)
      |> assign(max_age: nil, max_distance: @jump)
      |> assign_options(20, true)

    {:ok, socket}
  end

  # The courier moves on the server's clock, from the moment the map has
  # loaded. Each tick is a new lng_lat for the marker; the trail follows it
  # in the browser, so the LiveView never sends the path.

  @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

  def handle_event("step", _params, socket), do: {:noreply, advance(socket, 1)}

  # Across the round: a move longer than transition_max_distance, so the
  # courier jumps, and the trail breaks there with max_distance.
  def handle_event("jump", _params, socket), do: {:noreply, advance(socket, 6)}

  def handle_event("options", params, socket) do
    max_points =
      case Integer.parse(Map.get(params, "max_points", "")) do
        {count, ""} when count in 2..50 -> count
        _invalid -> socket.assigns.max_points
      end

    gradient = Map.get(params, "gradient", to_string(socket.assigns.gradient)) == "true"

    {:noreply, assign_options(socket, max_points, gradient)}
  end

  def handle_event("max_age", %{"seconds" => seconds}, socket) do
    case Enum.find(@max_ages, :none, &(shown(&1) == seconds)) do
      :none -> {:noreply, socket}
      max_age -> {:noreply, assign(socket, :max_age, max_age)}
    end
  end

  def handle_event("max_distance", %{"metres" => metres}, socket) do
    case Enum.find(@max_distances, :none, &(shown(&1) == metres)) do
      :none -> {:noreply, socket}
      max_distance -> {:noreply, assign(socket, :max_distance, max_distance)}
    end
  end

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

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

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

  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}, @interval)
    assign(socket, :clock, clock)
  end

  defp advance(socket, corners) do
    update(socket, :corner, &rem(&1 + corners, length(@round)))
  end

  defp assign_options(socket, max_points, gradient) do
    form = to_form(%{"max_points" => max_points, "gradient" => gradient})
    assign(socket, max_points: max_points, gradient: gradient, options: form)
  end

  # The corner as [longitude, latitude].
  defp corner(index) do
    {east, north} = Enum.at(@round, index)
    [lng, lat] = @centre
    metres_per_degree = 111_320 * :math.cos(lat * :math.pi() / 180)

    [Float.round(lng + east / metres_per_degree, 6), Float.round(lat + north / 110_574, 6)]
  end

  # The line fades from nothing at its tail (line-progress 0) to the
  # courier's colour at its head (1): the trail's source has line metrics.
  defp paint(true) do
    %{
      "line-width" => 4,
      "line-gradient" => [
        "interpolate",
        ["linear"],
        ["line-progress"],
        0,
        "rgba(124, 92, 214, 0)",
        1,
        "rgba(124, 92, 214, 1)"
      ]
    }
  end

  defp paint(false), do: %{"line-width" => 4, "line-color" => "#7c5cd6"}

  defp interval, do: @interval
  defp jump, do: @jump
  defp max_ages, do: @max_ages
  defp max_distances, do: @max_distances

  defp shown(nil), do: "nil"
  defp shown(number), do: Integer.to_string(number)
end