Skip to content

Wind and ocean currents

Particles that follow the wind at 10 m from a NOAA forecast, or the ocean surface currents NOAA measures from space, coloured by speed, with the flow at a clicked point.

Field

Speed

0 3 6 9 12 15 20 30
m/s
0 5.8 12 17 23 29 39 58
kn

Wind at 10 m. NOAA/NCEP Global Forecast System (GFS), republished by PacIOOS: the forecast for 2026-11-30 00:00 UTC, on a 1° grid. Dataset, licence.

Click the map for the flow there. towards is the direction the flow goes to, in degrees clockwise from north, as the particles move; a wind is named by the direction it comes from, the opposite one.

@variable
wind
@preset
wind_flow
@point
—
@speed
—
@towards
—
@from
—
lib/maplibrex_demo_web/scenarios/flow_scenario.html.heex
<div id="flow-scenario">
  <.example_frame error={@map_error} error_id="scenario-flow-map-error" tall>
    <%!-- Dark in both themes: the colour ramps are drawn for a dark ground. --%>
    <.map
      id="scenario-flow-map"
      center={[-35, 30]}
      zoom={1.8}
      style="https://tiles.openfreemap.org/styles/dark"
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- The field is an image: red is u, green is v, over u_range and
        v_range, and bounds are its outer edges. A new field, with its
        bounds and ranges, replaces the one drawn once it has loaded. The
        preset sets what is not given: here the colour ramp and the size of
        the particles. --%>
  <.flow_layer
    id="scenario-flow-layer"
    map_id="scenario-flow-map"
    field={@field.url}
    bounds={@field.bounds}
    u_range={@field.u_range}
    v_range={@field.v_range}
    preset={@preset}
    particles={@particles}
    speed_factor={@speed_factor}
    trail={@trail}
    opacity={@opacity}
    events={["flow:clicked", "flow:error"]}
  />

  <%!-- Credit for the field drawn, next to the basemap's. --%>
  <.attribution_control
    id="scenario-flow-attribution"
    map_id="scenario-flow-map"
    compact={false}
    custom_attribution={@field.attribution}
  />

  <.navigation_control id="scenario-flow-navigation" map_id="scenario-flow-map" />

  <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="scenario-flow-variables" label={gettext("Field")}>
        <.example_button
          :for={variable <- variables()}
          id={"scenario-flow-variable-#{variable}"}
          pressed={@variable == variable}
          phx-click="variable"
          phx-value-variable={variable}
        >
          {variable_name(variable)}
        </.example_button>
      </.example_group>

      <%!-- The preset's colour ramp, its stops evenly spaced. The bar and
            the speeds under it share a column, so that each speed sits
            under its colour. --%>
      <div id="scenario-flow-legend" class="max-w-sm min-w-48">
        <p class="mb-2 text-label font-bold text-ink-subtle">{gettext("Speed")}</p>
        <div class="grid grid-cols-[1fr_auto] items-center gap-x-2 gap-y-1">
          <div
            id="scenario-flow-legend-ramp"
            class="h-2.5 rounded-full ring-1 ring-line"
            style={gradient(ramp(@preset))}
          />
          <span></span>
          <%= for unit <- ["m/s", "kn"] do %>
            <div
              id={"scenario-flow-legend-#{if unit == "kn", do: "kn", else: "ms"}"}
              class="relative h-4 font-mono text-label text-ink-muted tabular-nums"
            >
              <span
                :for={{speed, _color, at} <- ticks(ramp(@preset))}
                class="absolute top-0 whitespace-nowrap"
                style={tick_style(at)}
              >
                {tick(speed, unit)}
              </span>
            </div>
            <span class="font-mono text-label text-ink-subtle">{unit}</span>
          <% end %>
        </div>
      </div>
    </div>

    <.form
      for={@options}
      id="scenario-flow-options"
      phx-change="options"
      class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4"
    >
      <.example_range
        field={@options[:particles]}
        label="particles"
        min="1000"
        max="30000"
        step="1000"
      />
      <%!-- Pixels a second per m/s: currents need ten times as many. --%>
      <.example_range
        field={@options[:speed_factor]}
        label="speed_factor"
        min="0"
        max={if @variable == "currents", do: "120", else: "12"}
        step={if @variable == "currents", do: "5", else: "0.5"}
      />
      <.example_range field={@options[:trail]} label="trail" min="0" max="0.99" step="0.01" />
      <.example_range field={@options[:opacity]} label="opacity" min="0" max="1" step="0.05" />
    </.form>

    <p
      :if={@field_error}
      id="scenario-flow-field-error"
      role="alert"
      class="flex items-start gap-1.5 text-label text-danger"
    >
      <.icon name="hero-exclamation-circle-micro" class="mt-px size-3.5 shrink-0" />
      <span>{gettext("The field could not be loaded: %{error}", error: @field_error)}</span>
    </p>

    <.example_note id="scenario-flow-source" icon="hero-clock-micro">
      <span class="font-bold">{variable_name(@variable)}.</span>
      {source(@variable, @field.time)}
      <.link href={@field.dataset_url} class="underline">{gettext("Dataset")}</.link>, <.link
        href={@field.license_url}
        class="underline"
      >{gettext("licence")}</.link>.
    </.example_note>
    <.example_note id="scenario-flow-click-hint" icon="hero-cursor-arrow-rays-micro">
      {gettext(
        "Click the map for the flow there. towards is the direction the flow goes to, in degrees clockwise from north, as the particles move; a wind is named by the direction it comes from, the opposite one."
      )}
    </.example_note>
  </div>

  <%!-- flow:clicked sets clicked: the flow at that point. --%>
  <.example_readout values={[
    variable: @variable,
    preset: @preset,
    point: point(@clicked),
    speed: speed(@clicked, @variable),
    towards: towards(@clicked),
    from: from(@clicked, @variable)
  ]} />
</div>
lib/maplibrex_demo_web/scenarios/flow_scenario.ex
defmodule MaplibrexDemoWeb.Scenarios.FlowScenario do
  @moduledoc """
  Wind and ocean currents: particles that follow a real vector field, drawn
  by `<.flow_layer>`, with trails coloured by speed.

  Two fields, each an image in `priv/static/fields/` with what describes it
  in `fields.json` (see `mix demo.fields`, which downloads them again):

    * wind at 10 m from NOAA/NCEP's Global Forecast System (GFS), in m/s;
    * ocean surface currents, geostrophic, from satellite altimetry, by NOAA
      CoastWatch, in m/s. Land has no data, and no particle goes there.

  A button switches `field`, with its `bounds`, `u_range` and `v_range`,
  and the `preset` for the kind of flow: the layer loads the new image and
  replaces the old one once it has loaded, without being rebuilt. The
  sliders set `particles`, `speed_factor`, `trail` and `opacity`, starting
  from the preset's values; the preset also gives the colour ramp, which
  the legend shows in m/s and knots.

  A click on the map comes back as `flow:clicked`, with the flow at that
  point: `speed`, and `direction`, the direction the flow goes towards in
  degrees clockwise from north (the oceanographic convention, and the way
  the particles move). Winds are given by the direction they come from (the
  meteorological convention), which is the opposite one. `flow:error` says
  that an image could not be loaded; the field drawn before stays.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  # Demo plumbing, not needed in an application: applies the page's locale
  # and reports each map event to the page.
  on_mount MaplibrexDemoWeb.Examples.Plumbing

  # What `mix demo.fields` wrote about each image, read when this module
  # compiles: a new download recompiles it.
  @fields_json Path.expand("../../../priv/static/fields/fields.json", __DIR__)
  @external_resource @fields_json
  @fields @fields_json |> File.read!() |> Jason.decode!()

  # Each field with its preset, and the preset's values, which the sliders
  # start from. Currents are about a tenth as fast as wind: their particles
  # move ten times as many pixels per m/s.
  @variables [
    {"wind",
     %{
       preset: "wind_flow",
       particles: 8000,
       speed_factor: 4.0,
       trail: 0.97,
       opacity: 0.9,
       speed_factor_max: 12
     }},
    {"currents",
     %{
       preset: "ocean_currents",
       particles: 10_000,
       speed_factor: 40.0,
       trail: 0.97,
       opacity: 0.9,
       speed_factor_max: 120
     }}
  ]

  # The colour ramp of each preset, {speed in m/s, colour}, as the flow
  # layer's documentation lists it: the legend shows it.
  @ramps %{
    "wind_flow" => [
      {0, "#3288bd"},
      {3, "#66c2a5"},
      {6, "#abdda4"},
      {9, "#e6f598"},
      {12, "#fee08b"},
      {15, "#fdae61"},
      {20, "#f46d43"},
      {30, "#d53e4f"}
    ],
    "ocean_currents" => [
      {0, "#253494"},
      {0.25, "#2c7fb8"},
      {0.5, "#41b6c4"},
      {1, "#a1dab4"},
      {2, "#ffffcc"}
    ]
  }

  @knots_per_metre_per_second 1.943844

  @impl true
  def mount(_params, _session, socket) do
    {:ok, socket |> assign(map_error: nil) |> assign_variable("wind")}
  end

  # Driven from the server: a button switches the field, and the sliders set
  # the layer's attributes.

  @impl true
  def handle_event("variable", %{"variable" => variable}, socket) do
    if List.keymember?(@variables, variable, 0) do
      {:noreply, assign_variable(socket, variable)}
    else
      {:noreply, socket}
    end
  end

  def handle_event("options", params, socket) do
    %{particles: particles, speed_factor: speed_factor, trail: trail, opacity: opacity} =
      socket.assigns

    {:noreply,
     socket
     |> assign(
       particles: params["particles"] |> integer(particles) |> clamp(1000, 30_000),
       speed_factor:
         params["speed_factor"] |> float(speed_factor) |> clamp(0, speed_factor_max(socket)),
       trail: params["trail"] |> float(trail) |> clamp(0, 0.99),
       opacity: params["opacity"] |> float(opacity) |> clamp(0, 1)
     )
     |> assign_options()}
  end

  # The flow where the map was clicked, in the field's units (m/s).
  # `direction` is where the flow goes; nil where it is still.
  def handle_event(
        "flow:clicked",
        %{"lngLat" => [lng, lat], "speed" => speed, "direction" => towards},
        socket
      )
      when is_number(lng) and is_number(lat) and is_number(speed) do
    towards = if is_number(towards), do: towards

    {:noreply, assign(socket, clicked: %{lng: lng, lat: lat, speed: speed, towards: towards})}
  end

  def handle_event("flow:clicked", _payload, socket), do: {:noreply, socket}

  # The image could not be loaded; the field drawn before stays on the map.
  def handle_event("flow:error", %{"error" => message}, socket) do
    {:noreply, assign(socket, :field_error, message)}
  end

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

  # A field with its preset's values. What was clicked belonged to the
  # field before.
  defp assign_variable(socket, variable) do
    {^variable, values} = List.keyfind(@variables, variable, 0)

    socket
    |> assign(variable: variable, field: field(variable), clicked: nil, field_error: nil)
    |> assign(Map.take(values, [:preset, :particles, :speed_factor, :trail, :opacity]))
    |> assign_options()
  end

  defp field(variable) do
    %{
      "bounds" => bounds,
      "u_range" => u_range,
      "v_range" => v_range,
      "time" => time,
      "attribution" => attribution,
      "dataset_url" => dataset_url,
      "license_url" => license_url
    } = Map.fetch!(@fields, variable)

    %{
      url: field_url(variable),
      bounds: bounds,
      u_range: u_range,
      v_range: v_range,
      time: time,
      attribution: attribution,
      dataset_url: dataset_url,
      license_url: license_url
    }
  end

  defp field_url("wind"), do: ~p"/fields/wind-10m.png"
  defp field_url("currents"), do: ~p"/fields/currents.png"

  defp variables, do: Enum.map(@variables, &elem(&1, 0))

  defp variable_name("wind"), do: gettext("Wind at 10 m")
  defp variable_name("currents"), do: gettext("Ocean surface currents")

  defp source("wind", time) do
    gettext(
      "NOAA/NCEP Global Forecast System (GFS), republished by PacIOOS: the forecast for %{time}, on a 1° grid.",
      time: format_time(time)
    )
  end

  defp source("currents", time) do
    gettext(
      "NOAA CoastWatch, geostrophic currents from satellite altimetry, near real time: the day of %{time}, on a 1° grid. Land and sea ice have no data.",
      time: format_time(time)
    )
  end

  defp format_time(time) do
    {:ok, datetime, 0} = DateTime.from_iso8601(time)
    Calendar.strftime(datetime, "%Y-%m-%d %H:%M UTC")
  end

  defp speed_factor_max(socket) do
    {_variable, %{speed_factor_max: max}} = List.keyfind(@variables, socket.assigns.variable, 0)
    max
  end

  # The legend: the stops of the preset's ramp, evenly spaced, as a CSS
  # gradient and as tick marks in m/s and knots. The layer interpolates
  # colours by speed between two stops, as the gradient does between their
  # places: the scale is linear from stop to stop.
  defp ramp(preset), do: Map.fetch!(@ramps, preset)

  defp ticks(ramp) do
    last = length(ramp) - 1

    for {{speed, color}, i} <- Enum.with_index(ramp),
        do: {speed, color, Float.round(i / last * 100, 2)}
  end

  defp gradient(ramp) do
    stops = Enum.map_join(ticks(ramp), ", ", fn {_speed, color, at} -> "#{color} #{at}%" end)
    "background: linear-gradient(to right, #{stops})"
  end

  # A tick label centred on its stop; the first and last stay inside the bar.
  defp tick_style(at) do
    shift =
      cond do
        at == 0 -> "0"
        at == 100 -> "-100%"
        true -> "-50%"
      end

    "left: #{at}%; transform: translateX(#{shift})"
  end

  defp knots(speed), do: speed * @knots_per_metre_per_second

  # Speeds shown as m/s and knots; currents, which are slow, with two decimals.
  defp format_speed(speed, "currents"), do: :erlang.float_to_binary(speed * 1.0, decimals: 2)
  defp format_speed(speed, _variable), do: :erlang.float_to_binary(speed * 1.0, decimals: 1)

  # Knots in whole numbers from 10 up, to one decimal below.
  defp tick(speed, "kn") do
    knots = knots(speed)
    if knots >= 10, do: number(round(knots)), else: number(Float.round(knots, 1))
  end

  defp tick(speed, "m/s"), do: number(speed)

  defp number(value) when is_integer(value), do: Integer.to_string(value)
  defp number(value) when value == trunc(value), do: Integer.to_string(trunc(value))
  defp number(value), do: Float.to_string(value)

  # The readout of a click.
  defp point(nil), do: "—"

  defp point(%{lng: lng, lat: lat}) do
    "#{degrees(abs(lat))}° #{if lat < 0, do: "S", else: "N"}, " <>
      "#{degrees(abs(lng))}° #{if lng < 0, do: "W", else: "E"}"
  end

  defp speed(nil, _variable), do: "—"

  defp speed(%{speed: speed}, variable) do
    "#{format_speed(speed, variable)} m/s · #{format_speed(knots(speed), variable)} kn"
  end

  # Whole degrees from 0 to 359: 359.6 is 0.
  defp towards(%{towards: towards}) when is_number(towards), do: "#{bearing(towards)}°"
  defp towards(_clicked), do: "—"

  # Where the wind comes from: the opposite of where it goes.
  defp from(%{towards: towards}, "wind") when is_number(towards),
    do: "#{rem(bearing(towards) + 180, 360)}°"

  defp from(_clicked, _variable), do: "—"

  defp bearing(degrees), do: rem(round(degrees), 360)

  defp degrees(value), do: :erlang.float_to_binary(value * 1.0, decimals: 2)

  defp assign_options(socket) do
    form =
      socket.assigns
      |> Map.take([:particles, :speed_factor, :trail, :opacity])
      |> Map.new(fn {key, value} -> {Atom.to_string(key), value} end)
      |> to_form()

    assign(socket, :options, form)
  end

  # Slider values arrive as strings: "8000", "0.97"; anything else keeps the
  # value.
  defp integer(value, current) do
    case Integer.parse(value || "") do
      {integer, _rest} -> integer
      :error -> current
    end
  end

  defp float(value, current) do
    case Float.parse(value || "") do
      {float, _rest} -> float
      :error -> current
    end
  end

  defp clamp(value, min, max), do: value |> max(min) |> min(max)
end