Skip to content

image_source

Stable

Places an image at four coordinates for a raster layer to draw.

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

lib/maplibrex_demo_web/examples/image_source_example.html.heex
<div id="image-source-example">
  <.example_frame
    error={@map_error}
    error_id="example-image-map-error"
    hosts={["tiles.openfreemap.org", "maplibre.org"]}
  >
    <.map
      id="example-image-map"
      center={[-75.97, 42.19]}
      zoom={4.6}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- The image is stretched between its four corners. A new url is
        applied to the source in place, without removing it. --%>
  <.image_source
    id="example-image-radar"
    map_id="example-image-map"
    url={frame_url(@frame)}
    coordinates={@corners}
    events={["source:added", "source:error"]}
  />

  <.raster_layer
    id="example-image-layer"
    map_id="example-image-map"
    source_id="example-image-radar"
    paint={%{"raster-opacity" => @opacity, "raster-fade-duration" => 0}}
  />

  <div class="space-y-4 border-t border-line px-4 py-4">
    <div class="grid gap-x-8 gap-y-4 lg:grid-cols-[auto_1fr]">
      <.example_group id="example-image-frames" label="url" code>
        <.example_button
          :for={frame <- frames()}
          id={"example-image-frame-#{frame}"}
          code
          pressed={@frame == frame}
          phx-click="frame"
          phx-value-frame={frame}
        >
          radar{frame}.gif
        </.example_button>
        <.example_button id="example-image-play" pressed={@playing} phx-click="play">
          <.icon
            name={if(@playing, do: "hero-pause-mini", else: "hero-play-mini")}
            class="size-4"
          />
          {if(@playing, do: gettext("Pause"), else: gettext("Play"))}
        </.example_button>
      </.example_group>

      <.form
        for={@options}
        id="example-image-options"
        phx-change="options"
        class="w-full sm:max-w-xs"
      >
        <.example_range
          field={@options[:opacity]}
          label="raster-opacity"
          min="0"
          max="1"
          step="0.05"
        />
      </.form>
    </div>

    <.example_note id="example-image-sample-data">
      {gettext(
        "Sample data: radar images from the MapLibre GL JS documentation, placed where its examples place them. They are not current weather."
      )}
    </.example_note>
  </div>

  <%!-- source:added sets status; the timer moves frame while playing. --%>
  <.example_readout values={[
    frame: @frame,
    playing: @playing,
    opacity: @opacity,
    status: @status
  ]} />
</div>
lib/maplibrex_demo_web/examples/image_source_example.ex
defmodule MaplibrexDemoWeb.Examples.ImageSourceExample do
  @moduledoc """
  The example of `<.image_source>`: an image placed at four coordinates and
  drawn by a raster layer. A new `url` from the server is applied to the
  source in place, so a timer on the server can animate it.
  """
  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"

  # Sample radar images from the MapLibre GL JS documentation, and the
  # corners its examples place them at: top left, top right, bottom right,
  # bottom left, as [longitude, latitude].
  @frames 0..4
  @corners [[-80.425, 46.437], [-71.516, 46.437], [-71.516, 37.936], [-80.425, 37.936]]

  @tick_ms 700

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(frame: 0, corners: @corners, playing: false, status: "waiting", map_error: nil)
      |> assign_opacity(0.8)

    {:ok, socket}
  end

  # Driven from the server: the frame is the image's url, the opacity is
  # the layer's paint.

  @impl true
  def handle_event("frame", %{"frame" => frame}, socket) do
    case Integer.parse(frame) do
      {frame, ""} when frame in @frames -> {:noreply, assign(socket, :frame, frame)}
      _ -> {: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

  # Playing is a timer on the server: every tick sets the next frame.
  def handle_event("play", _params, socket) do
    playing = not socket.assigns.playing
    if playing, do: Process.send_after(self(), :tick, @tick_ms)

    {:noreply, assign(socket, :playing, playing)}
  end

  # Events from the source: source:added says the image is on the map.

  def handle_event("source:added", _payload, socket) do
    {:noreply, assign(socket, :status, "added")}
  end

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

  @impl true
  def handle_info(:tick, %{assigns: %{playing: true}} = socket) do
    Process.send_after(self(), :tick, @tick_ms)
    {:noreply, update(socket, :frame, &rem(&1 + 1, Enum.count(@frames)))}
  end

  def handle_info(:tick, socket), do: {:noreply, socket}

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

  defp frames, do: @frames

  defp frame_url(frame), do: "https://maplibre.org/maplibre-gl-js/docs/assets/radar#{frame}.gif"
end