Skip to content

vector_tile_source

Stable

Adds vector tiles, from a TileJSON URL or a tile template, for layers to draw.

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

lib/maplibrex_demo_web/examples/vector_tile_source_example.html.heex
<div id="vector-tile-source-example">
  <.example_frame
    error={@map_error}
    error_id="example-vector-map-error"
    hosts={["tiles.openfreemap.org", "demotiles.maplibre.org"]}
  >
    <.map
      id="example-vector-map"
      center={[15, 25]}
      zoom={1.3}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- MapLibre's demo tiles: Natural Earth countries in a "countries" source
        layer, up to zoom 6. A tile template, so the attribution given here
        is the one shown. A source draws nothing itself: the layers below
        name it with source_id and pick the source layer to draw. --%>
  <.vector_tile_source
    :if={@enabled}
    id="example-vector-countries"
    map_id="example-vector-map"
    tiles={["https://demotiles.maplibre.org/tiles/{z}/{x}/{y}.pbf"]}
    max_zoom={6}
    attribution="Natural Earth, MapLibre demo tiles"
    events={["source:added", "source:data", "source:removed", "source:error"]}
  />

  <.fill_layer
    :if={@enabled}
    id="example-vector-fill"
    map_id="example-vector-map"
    source_id="example-vector-countries"
    source_layer="countries"
    paint={fill_paint(@continent)}
  />

  <.line_layer
    :if={@enabled}
    id="example-vector-borders"
    map_id="example-vector-map"
    source_id="example-vector-countries"
    source_layer="countries"
    paint={%{"line-color" => "#7c5cd6", "line-width" => 0.6, "line-opacity" => 0.6}}
  />

  <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="example-vector-continents" label={gettext("Set assigns")}>
      <.example_button
        :for={continent <- continents()}
        id={"example-vector-continent-#{slug(continent)}"}
        pressed={@continent == continent}
        phx-click="continent"
        phx-value-continent={slug(continent)}
      >
        {continent_name(continent)}
      </.example_button>
    </.example_group>

    <.example_group id="example-vector-toggle" label=":if" code>
      <.form for={@options} id="example-vector-options" phx-change="options" class="py-1.5">
        <.example_checkbox field={@options[:enabled]} label="enabled" />
      </.form>
    </.example_group>
  </div>

  <%!-- source:added, source:data and source:removed keep status current. --%>
  <.example_readout values={[
    continent: @continent,
    enabled: @enabled,
    status: @status,
    data_events: @data_events
  ]} />
</div>
lib/maplibrex_demo_web/examples/vector_tile_source_example.ex
defmodule MaplibrexDemoWeb.Examples.VectorTileSourceExample do
  @moduledoc """
  The example of `<.vector_tile_source>`: MapLibre's public demo tiles of
  the world's countries, drawn by a fill and a line layer, added and removed
  with `:if`, with the source's events reporting its progress.
  """
  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"

  # Values of the tiles' CONTINENT field.
  @continents ["Africa", "Asia", "Europe", "North America", "South America", "Oceania"]

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(continent: "Europe", status: "waiting", data_events: 0, map_error: nil)
      |> assign_enabled(true)

    {:ok, socket}
  end

  # Driven from the server: the continent is part of the fill's paint, and
  # :if adds or removes the source together with its layers.

  @impl true
  def handle_event("continent", %{"continent" => slug}, socket) do
    case Enum.find(@continents, &(slug(&1) == slug)) do
      nil -> {:noreply, socket}
      continent -> {:noreply, assign(socket, :continent, continent)}
    end
  end

  def handle_event("options", %{"enabled" => enabled}, socket) do
    {:noreply, assign_enabled(socket, enabled == "true")}
  end

  # Events from the source. source:data arrives for every tile requested and
  # loaded; isSourceLoaded says whether every tile in view has arrived.

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

  def handle_event("source:data", %{"tile" => %{"isSourceLoaded" => loaded?}}, socket) do
    {:noreply,
     socket
     |> assign(:status, if(loaded?, do: "loaded", else: "loading"))
     |> update(:data_events, &(&1 + 1))}
  end

  # source:data without a tile: the source's metadata (its TileJSON) arriving.
  def handle_event("source:data", _payload, socket), do: {:noreply, socket}

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

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

  # The chosen continent in purple, the rest in a faint grey.
  defp fill_paint(continent) do
    %{
      "fill-color" => ["case", ["==", ["get", "CONTINENT"], continent], "#7c5cd6", "#d8d8e0"],
      "fill-opacity" => ["case", ["==", ["get", "CONTINENT"], continent], 0.55, 0.15]
    }
  end

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

  defp continents, do: @continents
  defp slug(continent), do: continent |> String.downcase() |> String.replace(" ", "_")

  defp continent_name("Africa"), do: gettext("Africa")
  defp continent_name("Asia"), do: gettext("Asia")
  defp continent_name("Europe"), do: gettext("Europe")
  defp continent_name("North America"), do: gettext("North America")
  defp continent_name("South America"), do: gettext("South America")
  defp continent_name("Oceania"), do: gettext("Oceania")
end