Skip to content

line_layer

Stable

Draws lines from a source, such as roads, routes or boundaries.

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

lib/maplibrex_demo_web/examples/line_layer_example.html.heex
<div id="line-layer-example">
  <.example_frame error={@map_error} error_id="example-line-map-error">
    <.map
      id="example-line-map"
      center={[2.3522, 48.8566]}
      zoom={11}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- OpenFreeMap's TileJSON: OpenStreetMap in the OpenMapTiles schema. --%>
  <.vector_tile_source
    id="example-line-osm"
    map_id="example-line-map"
    url="https://tiles.openfreemap.org/planet"
    events={["source:error"]}
  />

  <%!-- The filter keeps the main roads of the "transportation" layer.
        hit_width: the layer answers the pointer within that many pixels of
        a road, for its click and its cursor; nil, exactly over the line. --%>
  <.line_layer
    id="example-line-roads"
    map_id="example-line-map"
    source_id="example-line-osm"
    source_layer="transportation"
    filter={["in", ["get", "class"], ["literal", ["motorway", "trunk", "primary"]]]}
    layout={%{"line-cap" => "round", "line-join" => "round"}}
    paint={paint(@color, @width, @dashed)}
    events={["layer:feature_clicked"]}
    cursor="pointer"
    hit_width={@hit_width}
  />

  <div class="space-y-3 border-t border-line px-4 py-4">
    <.example_group id="example-line-assigns" label={gettext("Set assigns")}>
      <.example_button
        :for={{name, hex} <- colors()}
        id={"example-line-color-#{name}"}
        code
        pressed={@color == hex}
        phx-click="color"
        phx-value-color={hex}
      >
        <.example_swatch color={hex} />{hex}
      </.example_button>

      <.form
        for={@options}
        id="example-line-options"
        phx-change="options"
        class="grid w-full gap-4 pt-2 sm:max-w-lg sm:grid-cols-[1fr_auto] sm:items-end"
      >
        <.example_range field={@options[:width]} label="line-width" min="1" max="10" />
        <.example_checkbox field={@options[:dashed]} label="line-dasharray" />
      </.form>
    </.example_group>

    <%!-- hit_width: how far from a road a click still reaches it. --%>
    <.example_group id="example-line-hit-width" label="hit_width" code>
      <.example_button
        :for={hit_width <- hit_widths()}
        id={"example-line-hit-width-#{hit_width_label(hit_width)}"}
        code
        pressed={@hit_width == hit_width}
        phx-click="hit_width"
        phx-value-width={hit_width_label(hit_width)}
      >
        {hit_width_label(hit_width)}
      </.example_button>
    </.example_group>

    <.example_note id="example-line-data" icon="hero-cursor-arrow-rays-micro">
      {gettext(
        "Main roads from OpenStreetMap, in OpenFreeMap's tiles. Click one. With a hit_width, a click beside a road reaches it too: the pointer shows where."
      )}
    </.example_note>
  </div>

  <%!-- layer:feature_clicked sets selected and counts the click. --%>
  <.example_readout values={[
    color: @color,
    width: @width,
    dashed: @dashed,
    hit_width: hit_width_label(@hit_width),
    selected: @selected || "—",
    clicks: @clicks
  ]} />
</div>
lib/maplibrex_demo_web/examples/line_layer_example.ex
defmodule MaplibrexDemoWeb.Examples.LineLayerExample do
  @moduledoc """
  The example of `<.line_layer>`: the main roads of OpenStreetMap, from
  OpenFreeMap's vector tiles, drawn over the basemap. Colour, width and
  dashes are paint set from the assigns. `hit_width` widens the roads'
  pointer target, so that a thin road is clicked without aiming at it: a
  pointer cursor shows where a click reaches, and the readout counts the
  clicks that arrive.
  """
  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/positron"

  @colors [
    {"purple", "#7c5cd6"},
    {"teal", "#0f8b8d"},
    {"orange", "#d9480f"},
    {"red", "#c92a2a"}
  ]

  # How far from a road, in pixels, the layer answers the pointer: nil
  # answers exactly over the line it draws.
  @hit_widths [nil, 8, 16]

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(color: "#7c5cd6", selected: nil, map_error: nil)
      |> assign(hit_width: nil, clicks: 0)
      |> assign_options(3, false)

    {:ok, socket}
  end

  @impl true
  def handle_event("color", %{"color" => color}, socket) do
    if Enum.any?(@colors, fn {_name, hex} -> hex == color end) do
      {:noreply, assign(socket, :color, color)}
    else
      {:noreply, socket}
    end
  end

  def handle_event("options", %{"width" => width, "dashed" => dashed}, socket) do
    case Integer.parse(width) do
      {width, _rest} -> {:noreply, assign_options(socket, width, dashed == "true")}
      :error -> {:noreply, socket}
    end
  end

  def handle_event("hit_width", %{"width" => width}, socket) do
    case Enum.find(@hit_widths, :none, &(hit_width_label(&1) == width)) do
      :none -> {:noreply, socket}
      hit_width -> {:noreply, assign(socket, :hit_width, hit_width)}
    end
  end

  # A click on a road, or within hit_width of one, carries its feature;
  # OpenMapTiles names its kind "class".
  def handle_event("layer:feature_clicked", %{"feature" => feature}, socket) do
    {:noreply,
     socket
     |> assign(:selected, feature["properties"]["class"])
     |> update(:clicks, &(&1 + 1))}
  end

  def handle_event(event, %{"error" => message}, socket)
      when event in ["map:error", "source:error"] do
    {:noreply, assign(socket, :map_error, message)}
  end

  # Without dashes the property is left out, and MaplibreX sets it back to
  # MapLibre's default: a solid line.
  defp paint(color, width, dashed) do
    paint = %{"line-color" => color, "line-width" => width, "line-opacity" => 0.85}
    if dashed, do: Map.put(paint, "line-dasharray", [2, 1]), else: paint
  end

  defp assign_options(socket, width, dashed) do
    assign(socket,
      width: width,
      dashed: dashed,
      options: to_form(%{"width" => width, "dashed" => dashed})
    )
  end

  defp colors, do: @colors

  defp hit_widths, do: @hit_widths

  defp hit_width_label(nil), do: "nil"
  defp hit_width_label(width), do: Integer.to_string(width)
end