Skip to content

3D terrain flight

Hillshading and 3D terrain from a public elevation service, with the exaggeration set from the server and camera flights between mountain ranges.

Set assigns

Run commands

@zoom
12
@pitch
70
@bearing
-20
@exaggeration
1.5
@terrain
true
lib/maplibrex_demo_web/scenarios/terrain_scenario.html.heex
<div id="terrain-scenario">
  <.example_frame
    error={@map_error}
    error_id="scenario-terrain-map-error"
    hosts={["tiles.openfreemap.org", "tiles.mapterhorn.com"]}
    tall
  >
    <.map
      id="scenario-terrain-map"
      center={@start.center}
      zoom={@start.zoom}
      pitch={@start.pitch}
      bearing={@start.bearing}
      max_pitch={85}
      style={basemap(@theme)}
      events={["map:moved", "map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

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

  <%!-- Terrain and hillshading each read their own DEM source: MapLibre
        warns when one raster-dem source backs both. --%>
  <.raster_dem_source
    id="scenario-terrain-dem"
    map_id="scenario-terrain-map"
    url="https://tiles.mapterhorn.com/tilejson.json"
    events={["source:error"]}
  />
  <.raster_dem_source
    id="scenario-hillshade-dem"
    map_id="scenario-terrain-map"
    url="https://tiles.mapterhorn.com/tilejson.json"
    events={["source:error"]}
  />

  <.hillshade_layer
    id="scenario-hillshade"
    map_id="scenario-terrain-map"
    source_id="scenario-hillshade-dem"
    paint={hillshade(@theme)}
  />

  <.terrain
    :if={@terrain}
    map_id="scenario-terrain-map"
    source_id="scenario-terrain-dem"
    exaggeration={@exaggeration}
    events={["terrain:error"]}
  />

  <div class="grid gap-x-8 gap-y-4 border-t border-line px-4 py-4 lg:grid-cols-[1fr_auto]">
    <.example_group id="scenario-terrain-assigns" label={gettext("Set assigns")}>
      <.form
        for={@options}
        id="scenario-terrain-options"
        phx-change="options"
        class="grid w-full gap-4 sm:max-w-lg sm:grid-cols-[1fr_auto] sm:items-end"
      >
        <.example_range
          field={@options[:exaggeration]}
          label="exaggeration"
          min="0.5"
          max="3"
          step="0.1"
        />
        <.example_checkbox field={@options[:terrain]} label=":if" />
      </.form>
    </.example_group>

    <%!-- Flights run in the browser: fly_to/4 returns a JS command. --%>
    <.example_group id="scenario-terrain-flights" label={gettext("Run commands")}>
      <.example_button
        :for={flight <- flights()}
        id={"scenario-terrain-fly-#{flight.id}"}
        phx-click={
          MapCmd.fly_to("scenario-terrain-map", flight.center, flight.zoom,
            duration: 4000,
            pitch: flight.pitch,
            bearing: flight.bearing
          )
        }
      >
        {flight.name}
      </.example_button>
    </.example_group>
  </div>

  <%!-- The camera as map:moved reports it, and the terrain's assigns. --%>
  <.example_readout values={[
    zoom: @zoom,
    pitch: @pitch,
    bearing: @bearing,
    exaggeration: @exaggeration,
    terrain: @terrain
  ]} />
</div>
lib/maplibrex_demo_web/scenarios/terrain_scenario.ex
defmodule MaplibrexDemoWeb.Scenarios.TerrainScenario do
  @moduledoc """
  3D terrain flight: hillshading and 3D terrain from Mapterhorn's public
  elevation tiles, with the exaggeration set from the server and camera
  flights between mountain ranges that run in the browser.

  A scenario is a LiveView like a component example, with its template next
  to it (`terrain_scenario.html.heex`); `MaplibrexDemoWeb.ScenarioLive`
  runs it and shows both files.
  """
  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,
  # reports each map event to the page 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"

  # Warm hillshading: cream highlights on the light basemap; on the dark
  # one, muted highlights and black shadows, so its light labels still read.
  defp hillshade(theme) do
    {shadow, highlight} =
      if theme == "dark", do: {"#000000", "#5e5646"}, else: {"#473b24", "#fff8e7"}

    %{
      "hillshade-exaggeration" => 0.7,
      "hillshade-shadow-color" => shadow,
      "hillshade-highlight-color" => highlight,
      "hillshade-illumination-anchor" => "map"
    }
  end

  # Each flight ends on a camera pitched and turned towards a range; a lower
  # zoom keeps the camera above the peaks around it.
  @flights [
    %{id: "innsbruck", center: [11.3909, 47.2757], zoom: 12, pitch: 70, bearing: -20},
    %{id: "matterhorn", center: [7.6586, 45.9763], zoom: 11.5, pitch: 65, bearing: -125},
    %{id: "dolomites", center: [12.3047, 46.6455], zoom: 12.5, pitch: 70, bearing: 180}
  ]

  @impl true
  def mount(_params, _session, socket) do
    start = hd(@flights)

    socket =
      socket
      |> assign(start: start, exaggeration: 1.5, terrain: true, map_error: nil)
      |> assign(zoom: start.zoom, pitch: start.pitch, bearing: start.bearing)
      |> assign_options()

    {:ok, socket}
  end

  # Driven from the server: the terrain follows exaggeration, and :if turns
  # it off and on. The flights are JS commands and need no handler.

  @impl true
  def handle_event("options", %{"exaggeration" => exaggeration, "terrain" => terrain}, socket) do
    {:noreply,
     socket
     |> assign(exaggeration: float(exaggeration), terrain: terrain == "true")
     |> assign_options()}
  end

  # The camera comes back with map:moved after a flight or a drag.
  def handle_event("map:moved", %{"zoom" => zoom, "pitch" => pitch, "bearing" => bearing}, socket) do
    {:noreply,
     assign(socket, zoom: round_to(zoom), pitch: round_to(pitch), bearing: round_to(bearing))}
  end

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

  defp flights do
    names = %{
      "innsbruck" => gettext("Innsbruck"),
      "matterhorn" => gettext("Matterhorn"),
      "dolomites" => gettext("Dolomites")
    }

    Enum.map(@flights, &Map.put(&1, :name, names[&1.id]))
  end

  defp assign_options(socket) do
    %{exaggeration: exaggeration, terrain: terrain} = socket.assigns
    assign(socket, :options, to_form(%{"exaggeration" => exaggeration, "terrain" => terrain}))
  end

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

  defp round_to(number) when is_integer(number), do: number
  defp round_to(number), do: Float.round(number, 2)
end