Skip to content

map

Stable

A MapLibre GL JS map whose center, zoom, pitch, bearing and style follow the LiveView's assigns.

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

lib/maplibrex_demo_web/examples/map_example.html.heex
<div id="map-example">
  <.example_frame error={@map_error} error_id="example-map-error">
    <%!-- fly: the map opens far out and flies to its camera, once, when it
          mounts; with reduced motion it opens there at once. projection:
          the flight starts from a globe, whatever the basemap declares.
          curtain: the map stays covered until its first render is complete,
          and the flight starts when the curtain lifts. follow: the id of
          a marker the camera keeps at the centre until the user drags the
          map; the map then pushes map:follow_ended. events: the map
          pushes these events to the LiveView, which has a handle_event/3
          clause for each, and no other; without it, it pushes none.
          Every other attribute follows its assign after mount. --%>
    <.map
      :if={@mounted}
      id="example-map"
      center={@center}
      zoom={@zoom}
      pitch={@pitch}
      bearing={@bearing}
      max_zoom={@max_zoom}
      interactive={@interactive}
      attribution_control={@attribution_control}
      style={basemap(@theme)}
      fly={%{from: %{zoom: 1.5}}}
      projection="globe"
      curtain
      follow={followed(@follow, @place)}
      events={["map:moved", "map:clicked", "map:error", "map:follow_ended"]}
      class="h-full w-full"
    >
      <%!-- Nested in <.map>: rendered right after the map element, so they
            follow the assigns and mount and unmount like components placed
            next to it. The chosen place's marker is purple. --%>
      <.marker
        :for={place <- place_list()}
        :if={@markers}
        id={"example-map-place-#{place.id}"}
        map_id="example-map"
        lng_lat={place.center}
        color={marker_color(place.id, @place)}
      />
    </.map>
  </.example_frame>

  <div class="grid gap-x-8 gap-y-4 border-t border-line px-4 py-4 lg:grid-cols-[1fr_auto]">
    <%!-- Assigns: each control changes an assign on the server; the map follows. --%>
    <.example_group id="example-assigns" label={gettext("Set assigns")}>
      <.example_button
        :for={{id, name} <- places()}
        id={"example-place-#{id}"}
        pressed={@place == id}
        phx-click="go"
        phx-value-place={id}
      >
        {name}
      </.example_button>

      <.form
        for={@camera}
        id="example-camera"
        phx-change="camera"
        class="grid w-full grid-cols-3 gap-4 pt-2"
      >
        <.input
          field={@camera[:zoom]}
          type="range"
          label="zoom"
          min="1"
          max="18"
          step="0.25"
          wrapper_class="font-mono text-label text-ink-subtle"
          class="mt-1 block w-full accent-accent"
        />
        <.input
          field={@camera[:pitch]}
          type="range"
          label="pitch"
          min="0"
          max="60"
          wrapper_class="font-mono text-label text-ink-subtle"
          class="mt-1 block w-full accent-accent"
        />
        <.input
          field={@camera[:bearing]}
          type="range"
          label="bearing"
          min="-180"
          max="180"
          wrapper_class="font-mono text-label text-ink-subtle"
          class="mt-1 block w-full accent-accent"
        />
      </.form>

      <.form
        for={@limits}
        id="example-limits"
        phx-change="limits"
        class="grid w-full gap-4 pt-1 sm:grid-cols-[1fr_auto_auto] sm:items-end"
      >
        <.example_range field={@limits[:max_zoom]} label="max_zoom" min="4" max="22" step="1" />
        <.example_checkbox field={@limits[:interactive]} label="interactive" />
        <.example_checkbox field={@limits[:attribution_control]} label="attribution_control" />
      </.form>

      <div class="flex flex-wrap gap-x-6 pt-1">
        <.form for={@markers_form} id="example-markers" phx-change="markers">
          <.example_checkbox field={@markers_form[:markers]} label=":if markers" />
        </.form>

        <%!-- Follows the chosen place's marker; another place moves the
              camera to its marker. Dragging the map ends it. --%>
        <.form for={@follow_form} id="example-follow" phx-change="follow">
          <.example_checkbox field={@follow_form[:follow]} label="follow" />
        </.form>
      </div>
    </.example_group>

    <div class="space-y-4">
      <%!-- Commands: JS structs that run in the browser, with no round trip. --%>
      <.example_group id="example-commands" label={gettext("Run commands")}>
        <.example_button id="example-zoom-in" code phx-click={MapCmd.zoom_in("example-map")}>
          zoom_in
        </.example_button>
        <.example_button id="example-zoom-out" code phx-click={MapCmd.zoom_out("example-map")}>
          zoom_out
        </.example_button>
        <.example_button
          id="example-reset-north"
          code
          phx-click={MapCmd.reset_north("example-map")}
        >
          reset_north
        </.example_button>
        <.example_button
          id="example-fly-home"
          code
          phx-click={MapCmd.fly_to("example-map", @home.center, @home.zoom, duration: 2000)}
        >
          fly_to
        </.example_button>
      </.example_group>

      <%!-- fly is read when the map mounts: the replay mounts a new map. --%>
      <.example_group id="example-fly" label="fly" code>
        <.example_button id="example-fly-replay" phx-click="replay">
          {gettext("Replay the flight")}
        </.example_button>
        <.example_note id="example-fly-note" icon="hero-information-circle-micro">
          {gettext("Once per mount. With reduced motion, the map opens where it lands.")}
        </.example_note>
      </.example_group>
    </div>
  </div>

  <%!-- The assigns as they are now: map:moved and map:clicked keep them current. --%>
  <.example_readout values={[
    place: @place,
    markers: @markers,
    center: lng_lat(@center),
    zoom: @zoom,
    pitch: @pitch,
    bearing: @bearing,
    last_click: lng_lat(@last_click),
    follow: followed(@follow, @place) || "nil",
    follow_ended: @follow_ended || "nil",
    max_zoom: @max_zoom,
    interactive: @interactive,
    attribution_control: @attribution_control
  ]} />
</div>
lib/maplibrex_demo_web/examples/map_example.ex
defmodule MaplibrexDemoWeb.Examples.MapExample do
  @moduledoc """
  The reference example for `<.map>`: an opening flight, a camera driven from
  the server, limits and options that follow the assigns after mount,
  commands that run in the browser, the map's events coming back, and
  components nested in the map that follow the assigns. `follow` keeps the
  chosen place's marker at the centre until the user drags the map, which
  `map:follow_ended` reports.

  An example is a LiveView of its own, with its template next to it
  (`map_example.html.heex`). The component page runs it with `live_render/3`
  and shows both files, read at compile time, so the code on the page is the
  code that runs.

  To add the example of another component, copy this module and its template
  to `<component>_example.ex` and `<component>_example.html.heex`, and set
  `example:` on the component in `MaplibrexDemoWeb.Catalogue`.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  alias MaplibreX.Components.Map, as: MapCmd

  # 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/liberty"

  @places [
    %{id: "madrid", center: [-3.7038, 40.4168], zoom: 11},
    %{id: "buenos_aires", center: [-58.3816, -34.6037], zoom: 11},
    %{id: "nairobi", center: [36.8219, -1.2921], zoom: 11}
  ]

  @home hd(@places)

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(home: @home, place: @home.id, markers: true, last_click: nil, map_error: nil)
      |> assign(:markers_form, to_form(%{"markers" => true}))
      |> assign(:follow_ended, nil)
      |> assign_follow(false)
      |> assign(:mounted, true)
      |> assign_camera(center: @home.center, zoom: @home.zoom, pitch: 0, bearing: 0)
      |> assign_limits(max_zoom: 22, interactive: true, attribution_control: true)

    {:ok, socket}
  end

  # Driven from the server: these only change assigns, and <.map> follows.

  @impl true
  def handle_event("go", %{"place" => id}, socket) do
    case Enum.find(@places, &(&1.id == id)) do
      nil ->
        {:noreply, socket}

      place ->
        {:noreply,
         socket
         |> assign(:place, place.id)
         |> assign_camera(center: place.center, zoom: place.zoom)}
    end
  end

  # :if on the nested markers: they mount and unmount with this assign.
  def handle_event("markers", %{"markers" => markers}, socket) do
    markers = markers == "true"
    {:noreply, assign(socket, markers: markers, markers_form: to_form(%{"markers" => markers}))}
  end

  # follow: the camera keeps the chosen place's marker at its centre, through
  # zooming and turning, until the user drags the map.
  def handle_event("follow", %{"follow" => follow}, socket) do
    {:noreply, assign_follow(socket, follow == "true")}
  end

  def handle_event("camera", %{"zoom" => zoom, "pitch" => pitch, "bearing" => bearing}, socket) do
    {:noreply,
     assign_camera(socket, zoom: number(zoom), pitch: number(pitch), bearing: number(bearing))}
  end

  # The limits and options follow their assigns after mount too: a lower
  # max_zoom zooms the map out into the new range (and map:moved reports it),
  # interactive turns the mouse, touch and keyboard off and on.
  def handle_event("limits", params, socket) do
    %{"max_zoom" => max_zoom, "interactive" => interactive, "attribution_control" => attribution} =
      params

    max_zoom =
      case Integer.parse(max_zoom) do
        {max_zoom, ""} -> max_zoom
        _ -> socket.assigns.max_zoom
      end

    {:noreply,
     assign_limits(socket,
       max_zoom: max_zoom,
       interactive: interactive == "true",
       attribution_control: attribution == "true"
     )}
  end

  # `fly` is read when the map mounts, so the replay mounts a new map: this
  # reply takes the map out of the page, and the next one (handle_info below)
  # puts it back. The new map flies to the camera in the assigns.
  def handle_event("replay", _params, socket) do
    send(self(), :remount)
    {:noreply, assign(socket, :mounted, false)}
  end

  # Events from the map, the ones its `events` attribute names. MaplibreX
  # debounces map:moved by 150 ms, so keeping the camera in the assigns does
  # not flood the socket while panning.

  def handle_event("map:moved", camera, socket) do
    %{"center" => center, "zoom" => zoom, "pitch" => pitch, "bearing" => bearing} = camera

    {:noreply,
     socket
     |> assign(:map_error, nil)
     |> assign_camera(center: center, zoom: zoom, pitch: pitch, bearing: bearing)}
  end

  # Following has ended: the user took the map ("user"), or a new center
  # moved it ("command"). follow goes back to false, so that checking it
  # again follows again.
  def handle_event("map:follow_ended", %{"reason" => reason}, socket) do
    {:noreply, socket |> assign(:follow_ended, reason) |> assign_follow(false)}
  end

  def handle_event("map:clicked", %{"lngLat" => lng_lat}, socket) do
    {:noreply, assign(socket, :last_click, lng_lat)}
  end

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

  @impl true
  def handle_info(:remount, socket), do: {:noreply, assign(socket, :mounted, true)}

  # The camera lives in plain assigns, which <.map> reads, and in a form for
  # the sliders.
  defp assign_camera(socket, camera) do
    socket = assign(socket, camera)

    form =
      to_form(%{
        "zoom" => socket.assigns.zoom,
        "pitch" => socket.assigns.pitch,
        "bearing" => socket.assigns.bearing
      })

    assign(socket, :camera, form)
  end

  defp assign_limits(socket, limits) do
    socket = assign(socket, limits)

    %{max_zoom: max_zoom, interactive: interactive, attribution_control: attribution} =
      socket.assigns

    form =
      to_form(%{
        "max_zoom" => max_zoom,
        "interactive" => interactive,
        "attribution_control" => attribution
      })

    assign(socket, :limits, form)
  end

  defp assign_follow(socket, follow) do
    assign(socket, follow: follow, follow_form: to_form(%{"follow" => follow}))
  end

  # The id of the marker to follow: the chosen place's, or nil.
  defp followed(true, place), do: "example-map-place-#{place}"
  defp followed(false, _place), do: nil

  defp place_list, do: @places

  defp marker_color(id, id), do: "#7c5cd6"
  defp marker_color(_id, _current), do: "#63637a"

  defp places do
    names = %{
      "madrid" => gettext("Madrid"),
      "buenos_aires" => gettext("Buenos Aires"),
      "nairobi" => gettext("Nairobi")
    }

    Enum.map(@places, &{&1.id, names[&1.id]})
  end

  # Slider values arrive as strings: "14.5", "45", "-30".
  defp number(value) do
    case Integer.parse(value) do
      {integer, ""} -> integer
      _ -> value |> Float.parse() |> elem(0)
    end
  end

  defp lng_lat(nil), do: "—"
  defp lng_lat([lng, lat]), do: "#{Float.round(lng / 1, 4)}, #{Float.round(lat / 1, 4)}"
end