Skip to content

circle_layer

Stable

Draws points from a source as circles.

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

lib/maplibrex_demo_web/examples/circle_layer_example.html.heex
<div id="circle-layer-example">
  <.example_frame
    error={@map_error}
    error_id="example-circle-map-error"
    hosts={["tiles.openfreemap.org", "demotiles.maplibre.org"]}
  >
    <.map
      id="example-circle-map"
      center={[15, 25]}
      zoom={1.3}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- MapLibre's demo tiles: a point per country in the "centroids" layer.
        promote_id: each point's id is its NAME, which feature state finds
        it by. --%>
  <.vector_tile_source
    id="example-circle-countries"
    map_id="example-circle-map"
    tiles={["https://demotiles.maplibre.org/tiles/{z}/{x}/{y}.pbf"]}
    max_zoom={6}
    attribution="Natural Earth, MapLibre demo tiles"
    promote_id="NAME"
    events={["source:error"]}
  />

  <%!-- feature_state: the selected country's point has selected: true, and
        hover lights the point under the pointer, in the browser. The ring's
        paint reads both with ["feature-state", ...]. --%>
  <.circle_layer
    id="example-circle-layer"
    map_id="example-circle-map"
    source_id="example-circle-countries"
    source_layer="centroids"
    paint={paint(@color, @radius, @theme)}
    feature_state={selection(@selected)}
    hover
    events={["layer:feature_clicked"]}
  />

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

    <.example_group id="example-circle-selection" label="feature_state" code>
      <.example_button id="example-circle-clear" phx-click="clear" disabled={!@selected}>
        {gettext("Clear the selection")}
      </.example_button>
    </.example_group>

    <.example_note id="example-circle-data" icon="hero-cursor-arrow-rays-micro">
      {gettext(
        "A point per country, from MapLibre's demo tiles. Click one to select it: its feature state rings it. The point under the pointer is lit."
      )}
    </.example_note>
  </div>

  <%!-- layer:feature_clicked sets selected. --%>
  <.example_readout values={[color: @color, radius: @radius, selected: @selected || "—"]} />
</div>
lib/maplibrex_demo_web/examples/circle_layer_example.ex
defmodule MaplibrexDemoWeb.Examples.CircleLayerExample do
  @moduledoc """
  The example of `<.circle_layer>`: the point of every country in MapLibre's
  demo tiles drawn as a circle, whose colour and radius are paint set from
  the assigns, with a click coming back as `layer:feature_clicked`.

  The country clicked is selected through feature state: the layer's
  `feature_state` gives its point `selected: true`, which the ring's paint
  reads, and the source takes each point's id from its name (`promote_id`).
  With `hover`, the point under the pointer is lit in the browser, with
  nothing sent to the server.
  """
  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"}
  ]

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

    {:ok, socket}
  end

  # Driven from the server: paint is an assign, so a new value repaints the
  # layer in place.

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

  # A click on a circle carries the feature under the pointer: its country
  # is selected.
  def handle_event("layer:feature_clicked", %{"feature" => feature}, socket) do
    {:noreply, assign(socket, :selected, feature["properties"]["NAME"])}
  end

  def handle_event("clear", _params, socket), do: {:noreply, assign(socket, :selected, nil)}

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

  # The selected country as feature state: its id, the name the source
  # promotes, to `selected: true`. An empty map when none is selected, so
  # the layer takes the state off.
  defp selection(nil), do: %{}
  defp selection(name), do: %{name => %{selected: true}}

  # The ring: the ink of the page's theme around the selected point, and a
  # wider white one around the point under the pointer.
  defp paint(color, radius, theme) do
    selected? = ["boolean", ["feature-state", "selected"], false]
    hovered? = ["boolean", ["feature-state", "hover"], false]

    %{
      "circle-color" => color,
      "circle-radius" => radius,
      "circle-stroke-color" => ["case", selected?, ink(theme), "#ffffff"],
      "circle-stroke-width" => ["case", selected?, 3, hovered?, 3, 1.5]
    }
  end

  defp ink("dark"), do: "#e8e9f1"
  defp ink("light"), do: "#1f2330"

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

  defp colors, do: @colors
end