Skip to content

image

Stable

An image of your own on the map for symbol layers to draw: an icon from a URL, one icon in any colour with sdf, or a pulsing dot.

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

lib/maplibrex_demo_web/examples/image_example.html.heex
<div id="image-example">
  <.example_frame error={@map_error} error_id="example-image-map-error">
    <.map
      id="example-image-map"
      center={[-0.3575, 39.4635]}
      zoom={12.6}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- Each <.image> puts an image on the map under its id, for layers to
        name in icon-image. The SVG takes a size; sdf makes it one shape
        that a layer paints with icon-color. --%>
  <.image
    id="example-image-vehicle"
    map_id="example-image-map"
    url="/images/vehicle.svg"
    width={24}
    height={24}
    sdf
    pixel_ratio={2}
  />

  <.image
    id="example-image-alert"
    map_id="example-image-map"
    animation={:pulse}
    color={@color}
    period={@period}
    size={64}
    pixel_ratio={2}
  />

  <.geojson_layer
    id="example-image-vehicles"
    map_id="example-image-map"
    type="symbol"
    data={fleet(@alerts)}
    layout={
      %{
        "icon-image" => "example-image-vehicle",
        "icon-rotate" => ["get", "heading"],
        "icon-rotation-alignment" => "map",
        "icon-allow-overlap" => true
      }
    }
    paint={
      %{"icon-color" => icon_color(), "icon-halo-color" => halo(@theme), "icon-halo-width" => 1.5}
    }
  />

  <%!-- The pulse under the vehicles in alert: before_id draws it below them. --%>
  <.geojson_layer
    id="example-image-alerts"
    map_id="example-image-map"
    type="symbol"
    data={fleet(@alerts)}
    filter={["get", "alert"]}
    before_id="example-image-vehicles"
    layout={%{"icon-image" => "example-image-alert", "icon-allow-overlap" => true}}
  />

  <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-colors" label="color" code>
        <.example_button
          :for={{name, hex} <- colors()}
          id={"example-image-color-#{name}"}
          code
          pressed={@color == hex}
          phx-click="pulse_color"
          phx-value-color={hex}
        >
          <.example_swatch color={hex} />{hex}
        </.example_button>
      </.example_group>

      <.example_group id="example-image-alert-toggles" label={gettext("Vehicles in alert")}>
        <.example_button
          :for={vehicle <- vehicles()}
          id={"example-image-alert-#{vehicle.id}"}
          code
          pressed={vehicle.id in @alerts}
          phx-click="alert"
          phx-value-id={vehicle.id}
        >
          {vehicle.id}
        </.example_button>
      </.example_group>
    </div>

    <.form
      for={@options}
      id="example-image-options"
      phx-change="options"
      class="w-full sm:max-w-xs"
    >
      <.example_range field={@options[:period]} label="period" min="500" max="3000" step="250" />
    </.form>

    <.example_note id="example-image-data">
      {gettext(
        "Sample vehicles, not real ones: teal is moving, orange idle and grey stopped. Visitors who ask for less motion see the pulse still."
      )}
    </.example_note>
  </div>

  <.example_readout values={[color: @color, period: @period, alerts: shown(@alerts)]} />
</div>
lib/maplibrex_demo_web/examples/image_example.ex
defmodule MaplibrexDemoWeb.Examples.ImageExample do
  @moduledoc """
  The example of `<.image>`: a fleet drawn by a symbol layer. One `sdf` icon,
  an SVG of the demo's, is tinted by each vehicle's status and turned to its
  heading; a pulsing image, `animation={:pulse}`, is drawn under the vehicles
  in alert, with the colour and period the assigns give 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"

  # The icons' halo takes the colour of the page's ground, so they read on
  # either basemap.
  defp halo("dark"), do: "#12141b"
  defp halo("light"), do: "#ffffff"

  # Sample vehicles around Valencia: where each is, where it heads (degrees
  # clockwise from north) and its status.
  @vehicles [
    %{id: "VAN-1", lng_lat: [-0.3445, 39.4705], heading: 30, status: "moving"},
    %{id: "VAN-2", lng_lat: [-0.372, 39.463], heading: 120, status: "idle"},
    %{id: "TRK-3", lng_lat: [-0.329, 39.4545], heading: 200, status: "moving"},
    %{id: "TRK-4", lng_lat: [-0.3605, 39.452], heading: 290, status: "stopped"},
    %{id: "VAN-5", lng_lat: [-0.385, 39.4745], heading: 75, status: "moving"}
  ]

  @colors [
    {"red", "#c92a2a"},
    {"orange", "#d9480f"},
    {"purple", "#7c5cd6"}
  ]

  # The pulse's period, in milliseconds, that the slider offers.
  @periods 500..3000

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(alerts: ["TRK-3"], color: "#c92a2a", map_error: nil)
      |> assign_period(1500)

    {:ok, socket}
  end

  # Driven from the server: the pulse's colour and period are attributes of
  # <.image>, which changes the animation from its next frame; the alerts
  # are data, which the layers' filter reads.

  @impl true
  def handle_event("pulse_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", %{"period" => period}, socket) do
    case Integer.parse(period) do
      {period, ""} when period in @periods -> {:noreply, assign_period(socket, period)}
      _invalid -> {:noreply, socket}
    end
  end

  def handle_event("alert", %{"id" => id}, socket) do
    if Enum.any?(@vehicles, &(&1.id == id)) do
      {:noreply, update(socket, :alerts, &toggle(&1, id))}
    else
      {:noreply, socket}
    end
  end

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

  # The vehicles as GeoJSON, each with its heading, status and alert flag.
  defp fleet(alerts) do
    %{
      "type" => "FeatureCollection",
      "features" =>
        for vehicle <- @vehicles do
          %{
            "type" => "Feature",
            "geometry" => %{"type" => "Point", "coordinates" => vehicle.lng_lat},
            "properties" => %{
              "id" => vehicle.id,
              "heading" => vehicle.heading,
              "status" => vehicle.status,
              "alert" => vehicle.id in alerts
            }
          }
        end
    }
  end

  # The icon's colour by status: a data-driven `icon-color`, which an sdf
  # image takes.
  defp icon_color do
    ["match", ["get", "status"], "moving", "#0f8b8d", "idle", "#d9480f", "#63637a"]
  end

  # In the order of the vehicles, so the readout and the layers agree.
  defp toggle(alerts, id) do
    alerts = if id in alerts, do: List.delete(alerts, id), else: [id | alerts]
    for %{id: id} <- @vehicles, id in alerts, do: id
  end

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

  defp vehicles, do: @vehicles
  defp colors, do: @colors

  defp shown([]), do: "—"
  defp shown(alerts), do: Enum.join(alerts, ", ")
end