Skip to content

background_layer

Stable

Paints the map background with a colour or a pattern.

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

lib/maplibrex_demo_web/examples/background_layer_example.html.heex
<div id="background-layer-example">
  <.example_frame
    error={@map_error}
    error_id="example-background-map-error"
    hosts={["demotiles.maplibre.org"]}
  >
    <%!-- A blank style, in both themes: the background and the land below
          are all the map draws, in the colour chosen here. --%>
    <.map
      id="example-background-map"
      center={[15, 25]}
      zoom={1.3}
      style={blank_style()}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- The background has no source, so it reaches the map first and the
        land is drawn over it. --%>
  <.background_layer
    id="example-background-layer"
    map_id="example-background-map"
    paint={%{"background-color" => @color, "background-opacity" => @opacity}}
  />

  <.vector_tile_source
    id="example-background-countries"
    map_id="example-background-map"
    tiles={["https://demotiles.maplibre.org/tiles/{z}/{x}/{y}.pbf"]}
    max_zoom={6}
    attribution="Natural Earth, MapLibre demo tiles"
    events={["source:error"]}
  />

  <.fill_layer
    id="example-background-land"
    map_id="example-background-map"
    source_id="example-background-countries"
    source_layer="countries"
    paint={%{"fill-color" => land(@theme), "fill-outline-color" => "#9a9db0"}}
  />

  <div class="space-y-3 border-t border-line px-4 py-4">
    <.example_group id="example-background-assigns" label={gettext("Set assigns")}>
      <.example_button
        :for={{name, hex} <- colors()}
        id={"example-background-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-background-options"
        phx-change="options"
        class="w-full pt-2 sm:max-w-xs"
      >
        <.example_range
          field={@options[:opacity]}
          label="background-opacity"
          min="0"
          max="1"
          step="0.05"
        />
      </.form>
    </.example_group>
  </div>

  <.example_readout values={[color: @color, opacity: @opacity]} />
</div>
lib/maplibrex_demo_web/examples/background_layer_example.ex
defmodule MaplibrexDemoWeb.Examples.BackgroundLayerExample do
  @moduledoc """
  The example of `<.background_layer>`: on a style with no layers of its
  own, the background is the sea behind the countries of MapLibre's demo
  tiles. Its colour and opacity are paint 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
  # and copies each map event to the page's Events tab.
  on_mount MaplibrexDemoWeb.Examples.Plumbing

  @colors [
    {"sea", "#b9d9eb"},
    {"teal", "#0f8b8d"},
    {"lavender", "#eee9f8"},
    {"ink", "#1f2330"}
  ]

  # A style with no sources or layers: the map draws only the layers below.
  @blank_style %{"version" => 8, "sources" => %{}, "layers" => []}

  @impl true
  def mount(_params, _session, socket) do
    # The sea starts light blue in the light theme and ink in the dark one
    # (Plumbing sets @theme); after that it is the visitor's choice.
    color = if socket.assigns.theme == "dark", do: "#1f2330", else: "#b9d9eb"

    socket =
      socket
      |> assign(color: color, map_error: nil)
      |> assign_opacity(1.0)

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

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

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

  defp colors, do: @colors
  defp blank_style, do: @blank_style

  # The land: white in the light theme, dark grey in the dark one.
  defp land("dark"), do: "#3d4255"
  defp land("light"), do: "#ffffff"
end