Skip to content

layer_switcher

Stable

A button in a corner of the map that opens a panel to choose the base map and turn overlays on and off.

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

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

  <%!-- OpenFreeMap's TileJSON: OpenStreetMap in the OpenMapTiles schema. The
        layers below are the example's: a style change keeps them. --%>
  <.vector_tile_source
    id="example-layer-switcher-osm"
    map_id="example-layer-switcher-map"
    url="https://tiles.openfreemap.org/planet"
    events={["source:error"]}
  />

  <.fill_layer
    id="example-layer-switcher-water"
    map_id="example-layer-switcher-map"
    source_id="example-layer-switcher-osm"
    source_layer="water"
    paint={%{"fill-color" => "#0f8b8d", "fill-opacity" => 0.5}}
  />

  <.fill_layer
    id="example-layer-switcher-buildings"
    map_id="example-layer-switcher-map"
    source_id="example-layer-switcher-osm"
    source_layer="building"
    paint={%{"fill-color" => "#d9480f", "fill-opacity" => 0.5}}
  />

  <.line_layer
    id="example-layer-switcher-roads"
    map_id="example-layer-switcher-map"
    source_id="example-layer-switcher-osm"
    source_layer="transportation"
    filter={["in", ["get", "class"], ["literal", ["motorway", "trunk", "primary"]]]}
    paint={%{"line-color" => "#7c5cd6", "line-width" => 3}}
  />

  <.line_layer
    id="example-layer-switcher-rail"
    map_id="example-layer-switcher-map"
    source_id="example-layer-switcher-osm"
    source_layer="transportation"
    filter={["==", ["get", "class"], "rail"]}
    paint={%{"line-color" => "#1971c2", "line-width" => 2}}
  />

  <%!-- The switcher: bases, one at a time, and overlays that hide and show
        their layers in the browser. Each entry has a key of its own, which
        names it in the events and in what remember keeps, whatever the
        language of its label. --%>
  <.layer_switcher
    id="example-layer-switcher"
    map_id="example-layer-switcher-map"
    label={gettext("Layers")}
    base_label={gettext("Base map")}
    open={@open}
    remember
    events={["layer_switcher:base_changed", "layer_switcher:overlay_toggled"]}
  >
    <:base :for={{key, label, style} <- bases()} key={key} label={label} style={style} />
    <:overlay
      key="roads"
      label={gettext("Main roads")}
      layers={["example-layer-switcher-roads"]}
      group={gettext("Transport")}
    />
    <:overlay
      key="rail"
      label={gettext("Railways")}
      layers={["example-layer-switcher-rail"]}
      group={gettext("Transport")}
    />
    <:overlay key="water" label={gettext("Water")} layers={["example-layer-switcher-water"]} />
    <:overlay
      key="buildings"
      label={gettext("Buildings")}
      layers={["example-layer-switcher-buildings"]}
      visible={false}
    />
  </.layer_switcher>

  <div class="space-y-3 border-t border-line px-4 py-4">
    <.example_group id="example-layer-switcher-assigns" label={gettext("Set assigns")}>
      <.form for={@options} id="example-layer-switcher-options" phx-change="options" class="pt-1">
        <.example_checkbox field={@options[:open]} label="open" />
      </.form>
    </.example_group>

    <.example_note id="example-layer-switcher-hint" icon="hero-cursor-arrow-rays-micro">
      {gettext(
        "Open the switcher in the map's top-right corner: choose a base map, and turn the overlays on and off. Your choice is kept in this browser for the next visit."
      )}
    </.example_note>
    <.example_note id="example-layer-switcher-theme" icon="hero-information-circle-micro">
      {gettext(
        "The page's theme switch gives the map a new style, as a LiveView may: that wins over the base chosen here, and the switcher shows the base of that style."
      )}
    </.example_note>
  </div>

  <%!-- layer_switcher:base_changed sets base, and
        layer_switcher:overlay_toggled sets overlay. --%>
  <.example_readout values={[open: @open, base: @base || "nil", overlay: @overlay || "nil"]} />
</div>
lib/maplibrex_demo_web/examples/layer_switcher_example.ex
defmodule MaplibrexDemoWeb.Examples.LayerSwitcherExample do
  @moduledoc """
  The example of `<.layer_switcher>`: Amsterdam from OpenFreeMap's tiles,
  with a switcher in the map's top-right corner. Its bases are three styles
  of OpenFreeMap, the two the page's themes use and a brighter one; its
  overlays are layers of the example, the main roads and the railways
  grouped under Transport, the water and the buildings on their own, the
  buildings off at first. Each entry has a `key` of its own, so that the
  events and what `remember` keeps do not change with the page's language.

  The page's theme switch gives the map a new `style`, as any LiveView may:
  that wins over the base the user chose, and the switcher shows the base
  of that style. A base chosen in the switcher stands as long as the theme
  does not change.
  """
  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 "https://tiles.openfreemap.org/styles/"

  # The bases: OpenFreeMap's styles by key. The map starts on the one of
  # the page's theme, which follows @theme.
  @bases [{"light", "positron"}, {"bright", "liberty"}, {"dark", "dark"}]

  defp basemap("dark"), do: @openfreemap <> "dark"
  defp basemap("light"), do: @openfreemap <> "positron"

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(base: nil, overlay: nil, map_error: nil)
      |> assign_options(false)

    {:ok, socket}
  end

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

  # The switcher changed the map in the browser, and says so.
  def handle_event("layer_switcher:base_changed", %{"key" => key}, socket) do
    {:noreply, assign(socket, :base, key)}
  end

  def handle_event(
        "layer_switcher:overlay_toggled",
        %{"key" => key, "visible" => visible},
        socket
      ) do
    {:noreply, assign(socket, :overlay, "#{key}: #{visible}")}
  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_options(socket, open) do
    assign(socket, open: open, options: to_form(%{"open" => open}))
  end

  defp bases do
    for {key, style} <- @bases, do: {key, base_label(key), @openfreemap <> style}
  end

  defp base_label("light"), do: gettext("Light")
  defp base_label("bright"), do: gettext("Bright")
  defp base_label("dark"), do: gettext("Dark")
end