Skip to content

geojson_layer

Stable

Draws GeoJSON data as a fill, line, circle, symbol, heatmap or fill-extrusion layer, with optional clustering and feature events.

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

lib/maplibrex_demo_web/examples/geojson_layer_example.html.heex
<div id="geojson-layer-example">
  <.example_frame error={@map_error} error_id="example-geojson-map-error">
    <.map
      id="example-geojson-map"
      center={@center}
      zoom={10}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

  <%!-- The layer sits next to <.map>, not inside it, and names it with map_id.
        Every point has an id, so a point that moves goes to the map alone,
        and moves there over transition ms. --%>
  <.geojson_layer
    :if={@visible}
    id="example-geojson-points"
    map_id="example-geojson-map"
    type="circle"
    data={@points}
    paint={paint(@color, @radius)}
    transition={@transition}
    events={["layer:feature_clicked"]}
    cursor={@cursor}
  />

  <div class="space-y-3 border-t border-line px-4 py-4">
    <div class="grid gap-x-8 gap-y-4 lg:grid-cols-[1fr_auto]">
      <%!-- Assigns: each control changes an assign; the layer follows. --%>
      <.example_group id="example-geojson-assigns" label={gettext("Set assigns")}>
        <.example_button
          :for={{name, hex} <- colors()}
          id={"example-geojson-color-#{name}"}
          code
          pressed={@color == hex}
          phx-click="color"
          phx-value-color={hex}
        >
          <.example_swatch color={hex} />{hex}
        </.example_button>

        <.form
          for={@options}
          id="example-geojson-options"
          phx-change="options"
          class="grid w-full gap-4 pt-2 sm:max-w-lg sm:grid-cols-[1fr_auto] sm:items-end"
        >
          <.example_range field={@options[:radius]} label="radius" min="3" max="20" />
          <.example_checkbox field={@options[:visible]} label="visible" />
        </.form>

        <%!-- cursor: the CSS cursor over the points, which needs no event.
              This layer asks for one, and shows it instead of the pointer. --%>
        <.example_group id="example-geojson-cursor" label="cursor" code>
          <.example_button
            :for={cursor <- cursors()}
            id={"example-geojson-cursor-#{cursor}"}
            code
            pressed={@cursor == cursor}
            phx-click="cursor"
            phx-value-cursor={cursor}
          >
            {cursor}
          </.example_button>
        </.example_group>
      </.example_group>

      <%!-- Commands: JS structs that hide and show the layer in the browser,
            with no round trip, where :if above removes it and its source. --%>
      <.example_group id="example-geojson-commands" label={gettext("Run commands")}>
        <.example_button
          id="example-geojson-hide"
          code
          disabled={!@visible}
          phx-click={LayerCmd.hide("example-geojson-points")}
        >
          hide
        </.example_button>
        <.example_button
          id="example-geojson-show"
          code
          disabled={!@visible}
          phx-click={LayerCmd.show("example-geojson-points")}
        >
          show
        </.example_button>
      </.example_group>
    </div>

    <%!-- Data: the next point moves out to a wider ring, or back in, as new
          data (all twelve points go over the socket) or as a
          layer:update_data push (the moved point alone). --%>
    <div class="grid gap-x-8 gap-y-4 lg:grid-cols-[1fr_auto]">
      <.example_group id="example-geojson-data" label={gettext("Change the data")}>
        <.example_button id="example-geojson-move" phx-click="move" disabled={!@visible}>
          {gettext("Move the next point")}
        </.example_button>
        <.form for={@motion} id="example-geojson-motion" phx-change="motion" class="w-full pt-1">
          <.example_range
            field={@motion[:transition]}
            label="transition"
            min="0"
            max="3000"
            step="250"
          />
        </.form>
      </.example_group>

      <.example_group id="example-geojson-sends" label={gettext("Send it as")}>
        <.example_button
          :for={send <- sends()}
          id={"example-geojson-send-#{send}"}
          code
          pressed={@send == send}
          phx-click="send"
          phx-value-send={send}
        >
          {send_label(send)}
        </.example_button>
      </.example_group>
    </div>

    <.example_note id="example-geojson-sample-data">
      {gettext("Sample data: twelve points placed on a ring for this example. Click one.")}
    </.example_note>
  </div>

  <%!-- The assigns as they are now: layer:feature_clicked sets selected. --%>
  <.example_readout values={[
    color: @color,
    radius: @radius,
    visible: @visible,
    cursor: @cursor,
    transition: @transition,
    send: send_label(@send),
    moved: @moved || "nil",
    selected: @selected || "—"
  ]} />
</div>
lib/maplibrex_demo_web/examples/geojson_layer_example.ex
defmodule MaplibrexDemoWeb.Examples.GeojsonLayerExample do
  @moduledoc """
  The example of `<.geojson_layer>`: GeoJSON points drawn as a circle layer
  whose paint and `cursor` follow assigns, added and removed with `:if`,
  hidden and shown in the browser by commands, with the clicked point coming
  back as `layer:feature_clicked`. Every point has an id of its own, so a
  point moved from the server goes to the map alone, as new `data` or as a
  `layer:update_data` push, and moves there over `transition` milliseconds.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  alias MaplibreX.Components.GeoJSONLayer, as: LayerCmd

  # 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/liberty"

  @madrid [-3.7038, 40.4168]

  # Sample data: twelve points on a ring around Madrid, made up for this
  # example, numbered 1 to 12. A point moved out sits on a wider ring.
  @ring 1..12

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

  # CSS cursors to show over the points with `cursor`.
  @cursors ~w(pointer crosshair)

  # How a moved point reaches the layer: as new `data`, or pushed alone.
  @sends ~w(data push)

  # How long a point takes to move, in milliseconds, as the slider offers it.
  @transitions 0..3000

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(center: @madrid, selected: nil, map_error: nil)
      |> assign(color: "#7c5cd6", radius: 8, visible: true, cursor: "pointer")
      |> assign(out: MapSet.new(), next: 1, moved: nil, send: "data")
      |> assign(:points, points(MapSet.new()))
      |> assign_options()
      |> assign_motion(1000)

    {:ok, socket}
  end

  # Driven from the server: paint is an assign, so a new value repaints the
  # layer, and :if adds or removes it.

  @impl true
  def handle_event("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("cursor", %{"cursor" => cursor}, socket) do
    if cursor in @cursors do
      {:noreply, assign(socket, :cursor, cursor)}
    else
      {:noreply, socket}
    end
  end

  def handle_event("options", %{"radius" => radius, "visible" => visible}, socket) do
    visible = visible == "true"

    # A layer that :if mounts again starts from `data`: give it the points
    # as they are now, the pushed ones included.
    socket =
      if visible and not socket.assigns.visible,
        do: assign(socket, :points, points(socket.assigns.out)),
        else: socket

    {:noreply,
     socket
     |> assign(radius: integer(radius, socket.assigns.radius), visible: visible)
     |> assign_options()}
  end

  # The next point moves out to the wider ring, or back in. Every point has
  # an id, so the layer gives the map that point alone, and moves it over
  # `transition` ms.
  def handle_event("move", _params, socket) do
    %{next: i, out: out} = socket.assigns
    out = if i in out, do: MapSet.delete(out, i), else: MapSet.put(out, i)
    socket = assign(socket, out: out, next: rem(i, 12) + 1, moved: "Point #{i}")

    case socket.assigns.send do
      # New data: LiveView sends all twelve points, and the layer works out
      # in the browser that one changed.
      "data" ->
        {:noreply, assign(socket, :points, points(out))}

      # A push: only the moved point goes over the socket, and `data` stays
      # as it is.
      "push" ->
        {:noreply,
         push_event(socket, "layer:update_data", %{
           layer_id: "example-geojson-points",
           update: [point(i, i in out)]
         })}
    end
  end

  def handle_event("send", %{"send" => send}, socket) when send in @sends do
    {:noreply, assign(socket, :send, send)}
  end

  def handle_event("send", _params, socket), do: {:noreply, socket}

  def handle_event("motion", %{"transition" => transition}, socket) do
    case Integer.parse(transition) do
      {ms, ""} when ms in @transitions -> {:noreply, assign_motion(socket, ms)}
      _invalid -> {:noreply, socket}
    end
  end

  # Events from the layer: a click on a point carries its feature.

  def handle_event("layer:feature_clicked", %{"feature" => feature}, socket) do
    {:noreply, assign(socket, :selected, feature["properties"]["name"])}
  end

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

  # Each point has an id, its "id", and the name shown when it is clicked.
  defp point(i, out?) do
    angle = i * :math.pi() / 6
    [lng, lat] = @madrid
    scale = if out?, do: 1.5, else: 1.0

    %{
      "type" => "Feature",
      "id" => i,
      "geometry" => %{
        "type" => "Point",
        "coordinates" => [
          lng + 0.06 * scale * :math.cos(angle),
          lat + 0.045 * scale * :math.sin(angle)
        ]
      },
      "properties" => %{"name" => "Point #{i}"}
    }
  end

  defp points(out) do
    %{"type" => "FeatureCollection", "features" => for(i <- @ring, do: point(i, i in out))}
  end

  defp paint(color, radius) do
    %{
      "circle-color" => color,
      "circle-radius" => radius,
      "circle-stroke-color" => "#ffffff",
      "circle-stroke-width" => 2
    }
  end

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

  defp assign_motion(socket, transition) do
    assign(socket, transition: transition, motion: to_form(%{"transition" => transition}))
  end

  defp colors, do: @colors

  defp sends, do: @sends

  defp send_label("data"), do: "data"
  defp send_label("push"), do: "layer:update_data"

  defp cursors, do: @cursors

  # Slider values arrive as strings: "14".
  defp integer(value, fallback) do
    case Integer.parse(value) do
      {integer, _rest} -> integer
      :error -> fallback
    end
  end
end