Skip to content

legend

Stable

Says what the colours and symbols of the map mean, in a corner of the map, and hides and shows layers from its entries.

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

lib/maplibrex_demo_web/examples/legend_example.html.heex
<div id="legend-example">
  <.example_frame error={@map_error} error_id="example-legend-map-error">
    <.map
      id="example-legend-map"
      center={[-3.7038, 40.4168]}
      zoom={12.2}
      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-legend-osm"
    map_id="example-legend-map"
    url="https://tiles.openfreemap.org/planet"
    events={["source:error"]}
  />

  <.fill_layer
    id="example-legend-parks"
    map_id="example-legend-map"
    source_id="example-legend-osm"
    source_layer="park"
    paint={%{"fill-color" => parks(), "fill-opacity" => 0.45}}
  />

  <.line_layer
    id="example-legend-rail"
    map_id="example-legend-map"
    source_id="example-legend-osm"
    source_layer="transportation"
    filter={["==", ["get", "class"], "rail"]}
    paint={%{"line-color" => rail(), "line-width" => 2}}
  />

  <%!-- The districts' fill and the stations' colour read the palettes the
        legend reads too. --%>
  <.geojson_layer
    id="example-legend-districts"
    map_id="example-legend-map"
    type="fill"
    data={@districts}
    paint={%{"fill-color" => noise_color(), "fill-opacity" => 0.3}}
  />

  <.geojson_layer
    id="example-legend-stations"
    map_id="example-legend-map"
    type="circle"
    data={@stations}
    paint={
      %{
        "circle-color" => kind_color(),
        "circle-radius" => 6,
        "circle-stroke-color" => "#ffffff",
        "circle-stroke-width" => 1.5
      }
    }
  />

  <.marker id="example-legend-depot" map_id="example-legend-map" lng_lat={@depot}>
    <.depot_icon />
  </.marker>

  <%!-- The legend, rendered by the server: a square and a line that hide
        and show their layers in the browser, a circle for each kind of
        station, the depot drawn by its own icon, and the noise's scale. --%>
  <.legend
    id="example-legend"
    map_id="example-legend-map"
    position={@position}
    title={gettext("Madrid, sample map")}
    collapsible={@collapsible}
    events={["legend:layer_toggled"]}
  >
    <:item color={parks()} label={gettext("Parks")} layers={["example-legend-parks"]} />
    <:item
      color={rail()}
      shape={:line}
      label={gettext("Railways")}
      layers={["example-legend-rail"]}
    />
    <:item :for={{kind, color} <- kinds()} color={color} shape={:circle} label={kind_label(kind)} />
    <:item label={gettext("Depot")}><.depot_icon class="size-4" /></:item>
    <:gradient
      colors={noise_colors()}
      from={elem(noise_range(), 0)}
      to={elem(noise_range(), 1)}
      label={gettext("Noise")}
    />
  </.legend>

  <div class="space-y-3 border-t border-line px-4 py-4">
    <div class="grid gap-x-8 gap-y-4 lg:grid-cols-[auto_1fr]">
      <%!-- position: the corner of the map; a new value moves the legend. --%>
      <.example_group id="example-legend-position" label="position" code>
        <.example_button
          :for={position <- positions()}
          id={"example-legend-position-#{position}"}
          code
          pressed={@position == position}
          phx-click="position"
          phx-value-position={position}
        >
          {position}
        </.example_button>
      </.example_group>

      <.example_group id="example-legend-assigns" label={gettext("Set assigns")}>
        <.form for={@options} id="example-legend-options" phx-change="options" class="pt-1">
          <.example_checkbox field={@options[:collapsible]} label="collapsible" />
        </.form>
      </.example_group>
    </div>

    <.example_note id="example-legend-hint" icon="hero-cursor-arrow-rays-micro">
      {gettext(
        "Press Parks or Railways in the legend to hide or show them. With collapsible, its title folds it away."
      )}
    </.example_note>
    <.example_note id="example-legend-sample-data">
      {gettext(
        "Sample data: the stations, the depot and the districts' noise are made up; parks and railways are OpenStreetMap's, in OpenFreeMap's tiles."
      )}
    </.example_note>
  </div>

  <%!-- legend:layer_toggled sets toggled. --%>
  <.example_readout values={[
    position: @position,
    collapsible: @collapsible,
    toggled: @toggled || "nil"
  ]} />
</div>
lib/maplibrex_demo_web/examples/legend_example.ex
defmodule MaplibrexDemoWeb.Examples.LegendExample do
  @moduledoc """
  The example of `<.legend>`: a sample map of Madrid and the legend that
  says what it shows. Parks and railways come from OpenFreeMap's tiles,
  each a square and a line in the legend that hides and shows its layer;
  sample stations are circles coloured by kind, one item each; the depot is
  a marker, whose own drawing is its item's swatch; and sample districts
  are filled by their noise, a gradient in the legend.

  The palettes are written once, in Elixir: each feeds a layer's `paint`
  (a `match` by kind, an `interpolate` over the noise) and the legend's
  entries, so that the two say the same. The legend's corner and
  `collapsible` are set from the assigns; `legend:layer_toggled` says what
  the user hid or showed.
  """
  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"

  @madrid [-3.7038, 40.4168]

  # The palettes, once. The stations' kinds, by the value of their "kind"
  # property; the noise of the districts, in decibels, by stop.
  @kinds [{"metro", "#7c5cd6"}, {"train", "#0f8b8d"}, {"bus", "#d9480f"}]
  @noise [{45, "#ffe066"}, {60, "#f59f00"}, {75, "#c92a2a"}]
  @parks "#2f9e44"
  @rail "#1971c2"

  # Sample data: stations of each kind, in degrees east and north of the
  # centre, made up for this example.
  @stations [
    {"metro", {-0.012, 0.006}},
    {"metro", {0.004, -0.004}},
    {"metro", {0.016, 0.01}},
    {"train", {-0.002, -0.016}},
    {"train", {0.022, -0.012}},
    {"bus", {-0.02, -0.008}},
    {"bus", {0.01, 0.018}},
    {"bus", {-0.006, 0.016}}
  ]

  # Sample data: a 3 by 3 grid of districts around the centre, each with a
  # noise level made up for this example.
  @noise_levels [52, 61, 48, 68, 74, 57, 46, 63, 55]

  @positions ~w(top-left top-right bottom-left bottom-right)

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      # A top corner: at phone width MapLibre's attribution opens across the
      # bottom of the map, over a bottom corner.
      |> assign(position: "top-left", toggled: nil, map_error: nil)
      |> assign_options(false)
      # The data, once: it never changes, so LiveView never sends it again.
      |> assign(stations: stations(), districts: districts(), depot: depot())

    {:ok, socket}
  end

  @impl true
  def handle_event("position", %{"position" => position}, socket) when position in @positions do
    {:noreply, assign(socket, :position, position)}
  end

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

  def handle_event("options", %{"collapsible" => collapsible}, socket) do
    {:noreply, assign_options(socket, collapsible == "true")}
  end

  # A press on Parks or Railways: the legend hid or showed their layers in
  # the browser, and says so.
  def handle_event("legend:layer_toggled", %{"layers" => layers, "visible" => visible}, socket) do
    {:noreply, assign(socket, :toggled, "#{Enum.join(layers, ", ")}: #{visible}")}
  end

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

  # ["match", ["get", "kind"], "metro", "#7c5cd6", ..., "#63637a"]: the last
  # colour is for any other kind.
  defp kind_color do
    ["match", ["get", "kind"]] ++ Enum.flat_map(@kinds, &Tuple.to_list/1) ++ ["#63637a"]
  end

  # ["interpolate", ["linear"], ["get", "noise"], 45, "#ffe066", ...]: the
  # legend's gradient takes the colours of the same stops, in order.
  defp noise_color do
    ["interpolate", ["linear"], ["get", "noise"]] ++ Enum.flat_map(@noise, &Tuple.to_list/1)
  end

  defp noise_colors, do: Enum.map(@noise, &elem(&1, 1))

  defp noise_range do
    {{low, _}, {high, _}} = {List.first(@noise), List.last(@noise)}
    {"#{low} dB", "#{high} dB"}
  end

  defp kind_label("metro"), do: gettext("Metro")
  defp kind_label("train"), do: gettext("Train")
  defp kind_label("bus"), do: gettext("Bus")

  defp stations do
    [lng, lat] = @madrid

    features =
      for {{kind, {east, north}}, index} <- Enum.with_index(@stations, 1) do
        %{
          "type" => "Feature",
          "id" => index,
          "geometry" => %{"type" => "Point", "coordinates" => [lng + east, lat + north]},
          "properties" => %{"kind" => kind}
        }
      end

    %{"type" => "FeatureCollection", "features" => features}
  end

  defp districts do
    [lng, lat] = @madrid
    size = 0.016

    features =
      for {noise, index} <- Enum.with_index(@noise_levels) do
        west = lng + (rem(index, 3) - 1.5) * size
        south = lat + (div(index, 3) - 1.5) * size * 0.76
        {east, north} = {west + size, south + size * 0.76}

        %{
          "type" => "Feature",
          "id" => index + 1,
          "geometry" => %{
            "type" => "Polygon",
            "coordinates" => [
              [[west, south], [east, south], [east, north], [west, north], [west, south]]
            ]
          },
          "properties" => %{"noise" => noise}
        }
      end

    %{"type" => "FeatureCollection", "features" => features}
  end

  defp depot do
    [lng, lat] = @madrid
    [lng - 0.018, lat + 0.014]
  end

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

  defp kinds, do: @kinds
  defp positions, do: @positions
  defp parks, do: @parks
  defp rail, do: @rail

  # The depot's drawing: the marker on the map, and its item's swatch in the
  # legend.
  attr :class, :string, default: "size-7"

  defp depot_icon(assigns) do
    ~H"""
    <svg viewBox="0 0 24 24" class={@class} aria-hidden="true">
      <path d="M12 2 3 7v11h18V7z" fill="#1f2330" stroke="#ffffff" stroke-width="1.5" />
      <path d="M8 18v-6h8v6" fill="none" stroke="#ffffff" stroke-width="1.5" />
    </svg>
    """
  end
end