Skip to content

symbol_layer

Stable

Places icons and text labels from a source.

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

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

  <.symbol_layer
    id="example-symbol-labels"
    map_id="example-symbol-map"
    source_id="example-symbol-osm"
    source_layer="poi"
    layout={layout(@field, @size)}
    paint={%{"text-color" => @color, "text-halo-color" => halo(@theme), "text-halo-width" => 1.5}}
    events={["layer:feature_clicked"]}
  />

  <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]">
      <.example_group id="example-symbol-fields" label="text-field" code>
        <.example_button
          :for={field <- fields()}
          id={"example-symbol-field-#{field}"}
          code
          pressed={@field == field}
          phx-click="field"
          phx-value-field={field}
        >
          ["get", "{field}"]
        </.example_button>
      </.example_group>

      <.example_group id="example-symbol-assigns" label={gettext("Set assigns")}>
        <.example_button
          :for={{name, hex} <- colors()}
          id={"example-symbol-color-#{name}"}
          code
          pressed={@color == hex}
          phx-click="color"
          phx-value-color={hex}
        >
          <.example_swatch color={hex} />{hex}
        </.example_button>
      </.example_group>
    </div>

    <.form
      for={@options}
      id="example-symbol-options"
      phx-change="options"
      class="w-full sm:max-w-xs"
    >
      <.example_range field={@options[:size]} label="text-size" min="9" max="22" />
    </.form>

    <.example_note id="example-symbol-data" icon="hero-cursor-arrow-rays-micro">
      {gettext(
        "Points of interest in Vienna from OpenStreetMap, in OpenFreeMap's tiles. Click a label."
      )}
    </.example_note>
  </div>

  <%!-- layer:feature_clicked sets selected. --%>
  <.example_readout values={[
    field: @field,
    size: @size,
    color: @color,
    selected: @selected || "—"
  ]} />
</div>
lib/maplibrex_demo_web/examples/symbol_layer_example.ex
defmodule MaplibrexDemoWeb.Examples.SymbolLayerExample do
  @moduledoc """
  The example of `<.symbol_layer>`: text labels for OpenStreetMap's points
  of interest, from OpenFreeMap's vector tiles. The label's text and size
  are layout and its colour is paint, all set from the assigns.
  """
  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"

  # The labels' halo takes the colour of the page's ground, so they read on
  # either basemap.
  defp halo("dark"), do: "#12141b"
  defp halo("light"), do: "#ffffff"

  # The feature properties a label can show: the place's name, or its kind.
  @fields ~w(name class)

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

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(field: "name", color: "#7c5cd6", selected: nil, map_error: nil)
      |> assign_size(13)

    {:ok, socket}
  end

  # Driven from the server: text-field and text-size are layout, text-color
  # is paint; MaplibreX applies both in place.

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

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

  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", %{"size" => size}, socket) do
    case Integer.parse(size) do
      {size, _rest} -> {:noreply, assign_size(socket, size)}
      :error -> {:noreply, socket}
    end
  end

  def handle_event("layer:feature_clicked", %{"feature" => feature}, socket) do
    {:noreply, assign(socket, :selected, feature["properties"]["name"])}
  end

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

  # Text needs a font the map's glyphs provide; OpenFreeMap's styles serve
  # Noto Sans.
  defp layout(field, size) do
    %{
      "text-field" => ["get", field],
      "text-size" => size,
      "text-font" => ["Noto Sans Regular"],
      "text-max-width" => 8
    }
  end

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

  defp fields, do: @fields
  defp colors, do: @colors
end