Skip to content

draw

Stable

Lets the user draw and edit shapes on the map, such as geofences, from a toolbar of its own or the application's buttons, sends them to the LiveView as GeoJSON, and shows the shapes the LiveView gives it.

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

lib/maplibrex_demo_web/examples/draw_example.html.heex
<div id="draw-example">
  <.example_frame error={@map_error} error_id="example-draw-map-error">
    <.map
      id="example-draw-map"
      center={[4.8434, 45.7565]}
      zoom={12.8}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- The drawing's own toolbar, in the map's top-left corner. No mode is
        given: the toolbar sets it in the browser, and draw:mode_changed
        tells the LiveView. Its labels are the page's, in its language.
        draw:started and draw:cancelled open and close the form below. Its
        hook comes from maplibrex/draw (assets/js/app.js). --%>
  <.draw
    :if={@set_by == "toolbar"}
    id="example-draw"
    map_id="example-draw-map"
    modes={[:polygon, :rectangle, :circle, :select]}
    features={@geofences}
    fill_color={@fill_color}
    fill_opacity={0.25}
    outline_color={@fill_color}
    outline_width={2}
    toolbar="top-left"
    toolbar_labels={toolbar_labels()}
    events={[
      "draw:created",
      "draw:updated",
      "draw:deleted",
      "draw:started",
      "draw:cancelled",
      "draw:mode_changed"
    ]}
  />

  <%!-- The LiveView sets the mode, from @mode: with the toolbar, a button
        asks for its mode with draw:mode_changed; without it, the page's own
        buttons below set it. The geofences are the truth for the ids they
        name: an edit the LiveView puts back stays, a geofence taken out
        goes. --%>
  <.draw
    :if={@set_by != "toolbar"}
    id="example-draw"
    map_id="example-draw-map"
    mode={@mode}
    modes={[:polygon, :rectangle, :circle, :select]}
    features={@geofences}
    fill_color={@fill_color}
    fill_opacity={0.25}
    outline_color={@fill_color}
    outline_width={2}
    toolbar={if(@set_by == "toolbar_mode", do: "top-left")}
    toolbar_labels={toolbar_labels()}
    events={[
      "draw:created",
      "draw:updated",
      "draw:deleted",
      "draw:started",
      "draw:cancelled",
      "draw:mode_changed"
    ]}
  />

  <%!-- The page's own toolbar, when the drawing has none: each button sets
        the mode, and the active one is tinted. --%>
  <.control_group
    :if={@set_by == "buttons"}
    id="example-draw-tools"
    map_id="example-draw-map"
    position="top-left"
  >
    <.control_button
      :for={mode <- draw_modes()}
      id={"example-draw-tool-#{mode}"}
      map_id="example-draw-map"
      tooltip={tooltip(mode)}
      active={@mode == mode}
      class="grid! place-items-center"
      phx-click="draw_mode"
      phx-value-mode={mode}
    >
      <.tool_icon mode={mode} />
    </.control_button>
  </.control_group>

  <div class="space-y-4 border-t border-line px-4 py-4">
    <%!-- Who sets the mode. --%>
    <.example_group id="example-draw-setter" label={gettext("The mode is set by")}>
      <.example_button
        :for={setter <- setters()}
        id={"example-draw-setter-#{setter}"}
        pressed={@set_by == setter}
        phx-click="set_by"
        phx-value-setter={setter}
      >
        {setter_label(setter)}
      </.example_button>
      <p id="example-draw-setter-note" class="w-full pt-1 text-label text-ink-muted">
        {setter_note(@set_by)}
      </p>
    </.example_group>

    <%!-- The new geofence: draw:started opens the form, draw:created and
          draw:cancelled close it. --%>
    <div
      id="example-draw-draft"
      role="group"
      aria-labelledby="example-draw-draft-label"
      class="min-w-0"
    >
      <p id="example-draw-draft-label" class="mb-2 text-label font-bold text-ink-subtle">
        {gettext("New geofence")}
      </p>
      <p :if={!@draft} id="example-draw-draft-idle" class="text-ui text-ink-muted">
        {gettext("Start a shape on the map, and a form for its name opens here.")}
      </p>
      <.form
        :if={@draft}
        for={%{}}
        id="example-draw-draft-form"
        phx-change="draft"
        phx-submit="draft"
        class="flex flex-wrap items-end gap-x-4 gap-y-2"
      >
        <.input
          type="text"
          id="example-draw-draft-name"
          name="name"
          value={@draft.name}
          label={gettext("Name")}
          autocomplete="off"
          wrapper_class="w-56 text-label font-bold text-ink-subtle"
        />
        <p class="pb-2 text-ui text-ink-muted">
          {gettext("A %{mode} under way. Finish it on the map, or press Escape to give it up.",
            mode: @draft.mode
          )}
        </p>
      </.form>
    </div>

    <div class="grid gap-x-8 gap-y-4 lg:grid-cols-[auto_1fr]">
      <.example_group id="example-draw-colors" label="fill_color" code>
        <.example_button
          :for={{name, hex} <- colors()}
          id={"example-draw-color-#{name}"}
          code
          pressed={@fill_color == hex}
          phx-click="fill_color"
          phx-value-color={hex}
        >
          <.example_swatch color={hex} />{hex}
        </.example_button>
      </.example_group>

      <%!-- @geofences as the LiveView stores them: id, mode and, for a
            circle, its radius in metres. --%>
      <.example_group id="example-draw-fences" label="@geofences" code>
        <span
          :for={fence <- @geofences}
          id={"example-draw-fence-#{fence["id"]}"}
          class="inline-flex h-8 items-center gap-1.5 rounded-ui border border-line px-2.5 font-mono text-label text-ink"
        >
          <span class="text-ink-subtle">{fence["id"]}</span>
          <span :if={name(fence)} class="font-sans font-bold">{name(fence)}</span>
          {kind(fence)}
          <span :if={radius(fence)} class="text-ink-muted">{radius(fence)}</span>
        </span>
      </.example_group>
    </div>

    <.example_note id="example-draw-hint" icon="hero-cursor-arrow-rays-micro">
      {gettext(
        "Choose a tool in the map's top-left corner. A polygon takes a click per corner and closes on its first one; a rectangle or a circle takes two clicks. With select, drag a geofence or its corners, or the middle of a polygon's edge to add a corner, and press Delete to remove it."
      )}
    </.example_note>
  </div>

  <%!-- draw:created, draw:updated and draw:deleted keep @geofences current;
        draw:started and draw:cancelled set drawing and count the shapes
        given up. --%>
  <.example_readout values={[
    set_by: @set_by,
    mode: @mode || "nil",
    drawing: (@draft && @draft.mode) || "nil",
    cancelled: @cancelled,
    fill_color: @fill_color,
    geofences: length(@geofences),
    next_id: @next_id
  ]} />
</div>
lib/maplibrex_demo_web/examples/draw_example.ex
defmodule MaplibrexDemoWeb.Examples.DrawExample do
  @moduledoc """
  The example of `<.draw>`: a geofence editor. Two geofences, a polygon and
  a circle given by its centre and radius, come from `features` under
  integer ids; a shape the user draws is stored under the next id, which the
  reply to `draw:created` gives it on the map; edits and deletions come back
  as `draw:updated` and `draw:deleted`.

  Who sets the mode is the visitor's choice:

    * the drawing's own toolbar (`toolbar`), with no `mode` given: it sets
      the mode in the browser and tells the LiveView with
      `draw:mode_changed`;
    * the LiveView, with `mode`: the toolbar asks for a mode with
      `draw:mode_changed`, and the LiveView sets it;
    * the LiveView, from the page's own toolbar of `<.control_button>`s in a
      `<.control_group>`, with no toolbar on the drawing.

  The toolbar's labels follow the page's language (`toolbar_labels`).

  A form for the new geofence's name opens with `draw:started`, as the first
  point of a shape is placed, and closes with `draw:created`, which stores
  the shape under that name, or `draw:cancelled`, when the shape is given
  up.
  """
  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 modes the toolbar offers, in its order: the drawing sets up these.
  @draw_modes ~w(polygon rectangle circle select)

  # Who sets the mode: the drawing's toolbar, the LiveView asked by that
  # toolbar, or the LiveView from the page's own buttons.
  @setters ~w(toolbar toolbar_mode buttons)

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

  # The most geofences kept: each one is kept in the LiveView.
  @max_geofences 50

  # Two stored geofences, as GeoJSON features under the ids a database would
  # give them. The station is stored as a centre and a radius in metres: a
  # Point of mode "circle", which the drawing shows as the circle.
  @geofences [
    %{
      "type" => "Feature",
      "id" => 1,
      "geometry" => %{
        "type" => "Polygon",
        "coordinates" => [
          [
            [4.851, 45.7655],
            [4.8625, 45.7668],
            [4.8648, 45.7578],
            [4.8545, 45.7552],
            [4.851, 45.7655]
          ]
        ]
      },
      "properties" => %{"mode" => "polygon"}
    },
    %{
      "type" => "Feature",
      "id" => 2,
      "geometry" => %{"type" => "Point", "coordinates" => [4.8262, 45.7497]},
      "properties" => %{"mode" => "circle", "radius" => 400}
    }
  ]

  @impl true
  def mount(_params, _session, socket) do
    {:ok,
     assign(socket,
       set_by: "toolbar",
       mode: nil,
       geofences: @geofences,
       next_id: 3,
       fill_color: "#7c5cd6",
       draft: nil,
       cancelled: 0,
       map_error: nil
     )}
  end

  # Who sets the mode. Each starts with none, as a drawing without `mode`
  # does.
  @impl true
  def handle_event("set_by", %{"setter" => setter}, socket) when setter in @setters do
    {:noreply, assign(socket, set_by: setter, mode: nil)}
  end

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

  # From the page's own toolbar: a tool sets the mode, and a second click on
  # the active one stops drawing. The guard keeps a mode the drawing does not
  # have, sent by a crafted click, from reaching it: <.draw> raises on one.

  def handle_event("draw_mode", %{"mode" => mode}, socket) when mode in @draw_modes do
    {:noreply, assign(socket, :mode, if(socket.assigns.mode == mode, do: nil, else: mode))}
  end

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

  # From the drawing's toolbar: the mode it set, or, with `mode` given, the
  # mode it asks for, nil for none. Either way @mode follows it; with `mode`
  # given, that is what sets the mode.
  def handle_event("draw:mode_changed", %{"mode" => mode}, socket)
      when mode in @draw_modes or is_nil(mode) do
    {:noreply, assign(socket, :mode, mode)}
  end

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

  def handle_event("fill_color", %{"color" => color}, socket) do
    if Enum.any?(@colors, fn {_name, hex} -> hex == color end) do
      {:noreply, assign(socket, :fill_color, color)}
    else
      {:noreply, socket}
    end
  end

  # A shape is under way: the form for its name opens. It closes when the
  # shape is finished (draw:created) or given up (draw:cancelled).
  def handle_event("draw:started", %{"mode" => mode}, socket) do
    {:noreply, assign(socket, :draft, %{mode: mode, name: ""})}
  end

  def handle_event("draw:cancelled", _params, socket) do
    {:noreply, socket |> assign(:draft, nil) |> update(:cancelled, &(&1 + 1))}
  end

  def handle_event("draft", %{"name" => name}, %{assigns: %{draft: %{} = draft}} = socket) do
    {:noreply, assign(socket, :draft, %{draft | name: name})}
  end

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

  # Events from the drawing. A shape the user drew arrives with an id of
  # Terra Draw's; the reply gives it the next id of the LiveView's, under
  # which it is stored, with the name the form gave it. The shape on the map
  # takes that id before the re-render that names it, so it never shows
  # twice, and its later events carry it.

  def handle_event(
        "draw:created",
        %{"feature" => feature},
        %{assigns: %{geofences: fences}} = socket
      )
      when length(fences) < @max_geofences do
    id = socket.assigns.next_id
    stored = feature |> Map.put("id", id) |> named(socket.assigns.draft)

    {:reply, %{id: id},
     socket
     |> assign(next_id: id + 1, draft: nil)
     |> update(:geofences, &(&1 ++ [stored]))}
  end

  # Past the cap the shape is not stored, and keeps the id Terra Draw gave it.
  def handle_event("draw:created", _params, socket) do
    {:noreply, assign(socket, :draft, nil)}
  end

  # An edit ends: the feature as it is now, a circle with its new "center"
  # and "radius". Put back in `features`, the edit stays on the map.
  def handle_event("draw:updated", %{"feature" => %{"id" => id} = feature}, socket) do
    {:noreply, update(socket, :geofences, &replace(&1, id, feature))}
  end

  def handle_event("draw:deleted", %{"feature" => %{"id" => id}}, socket) do
    {:noreply, update(socket, :geofences, &Enum.reject(&1, fn fence -> fence["id"] == id end))}
  end

  def handle_event("map:error", %{"error" => message}, socket) do
    {:noreply, assign(socket, :map_error, message)}
  end

  defp named(feature, %{name: name}) do
    case String.trim(name) do
      "" -> feature
      name -> put_in(feature, ["properties", "name"], name)
    end
  end

  defp named(feature, nil), do: feature

  defp replace(fences, id, feature) do
    Enum.map(fences, fn fence -> if fence["id"] == id, do: feature, else: fence end)
  end

  defp draw_modes, do: @draw_modes
  defp colors, do: @colors
  defp setters, do: @setters

  defp setter_label("toolbar"), do: gettext("Its toolbar")
  defp setter_label("toolbar_mode"), do: gettext("The LiveView, asked by its toolbar")
  defp setter_label("buttons"), do: gettext("The LiveView, from the page's buttons")

  defp setter_note("toolbar"),
    do:
      gettext(
        "With no mode given, the drawing's toolbar sets it in the browser, and tells the LiveView with draw:mode_changed."
      )

  defp setter_note("toolbar_mode"),
    do:
      gettext(
        "With mode given, a button of the toolbar asks for its mode with draw:mode_changed, and the LiveView sets it."
      )

  defp setter_note("buttons"),
    do:
      gettext(
        "The drawing has no toolbar: the page's own buttons set mode, as before MaplibreX had one."
      )

  # The toolbar's labels, in the page's language: the accessible name and
  # tooltip of each button.
  defp toolbar_labels do
    labels = for mode <- @draw_modes, into: %{}, do: {mode, tooltip(mode)}
    Map.put(labels, "cancel", gettext("Give up the shape being drawn"))
  end

  defp tooltip("polygon"), do: gettext("Draw a polygon")
  defp tooltip("rectangle"), do: gettext("Draw a rectangle")
  defp tooltip("circle"), do: gettext("Draw a circle")
  defp tooltip("select"), do: gettext("Select, move, reshape and delete geofences")

  # What the readout says of a geofence: its name, its mode, and a circle's
  # radius.
  defp kind(fence), do: fence["properties"]["mode"]
  defp name(fence), do: fence["properties"]["name"]

  defp radius(%{"properties" => %{"radius" => radius}}) when is_number(radius),
    do: "#{round(radius)} m"

  defp radius(_fence), do: nil

  # The toolbar's icons, drawn for the demo: a pentagon, a rectangle, a
  # circle and an arrow, in the button's colour.
  attr :mode, :string, required: true

  defp tool_icon(assigns) do
    ~H"""
    <svg
      viewBox="0 0 20 20"
      class="size-5"
      fill="none"
      stroke="currentColor"
      stroke-width="1.6"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path :if={@mode == "polygon"} d="M10 2.75 17.25 8l-2.75 8.25h-9L2.75 8z" />
      <rect :if={@mode == "rectangle"} x="3" y="5" width="14" height="10" rx="0.5" />
      <circle :if={@mode == "circle"} cx="10" cy="10" r="7" />
      <path
        :if={@mode == "select"}
        d="M5 3v12.5l3.5-3.25 2.25 5 2.25-1-2.25-5H15z"
        fill="currentColor"
        stroke-width="1"
      />
    </svg>
    """
  end
end