Skip to content

Clustered places

Sample data

Sample places drawn as clusters where they are close together on the screen: a click opens a cluster, and the places it held are listed beside the map, ten at a time.

Places listed

Click a cluster to list its places, or a place to list it alone.

Clusters drawn by

Page through the cluster

Sample data: 400 places generated around five parts of Lisbon, with a fixed seed. They are not real places.

A click on a cluster zooms in to where it breaks apart, in the browser, and the server asks the layer for the places it held, ten at a time.

@drawn
paint
@cluster_id
nil
@point_count
nil
@offset
nil
@request
0
@listed
0
lib/maplibrex_demo_web/scenarios/clusters_scenario.html.heex
<div id="clusters-scenario">
  <.example_frame error={@map_error} error_id="scenario-clusters-map-error" tall>
    <.map
      id="scenario-clusters-map"
      center={centre()}
      zoom={12.2}
      style={basemap(@theme)}
      events={["map:error"]}
      class="h-full w-full"
    />
  </.example_frame>

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

  <%!-- The places, clustered: cluster_expand_on_click opens a cluster on a
        click, in the browser, and layer:feature_clicked names it, with
        cluster_id and point_count. Each place's id is its place_id
        (promote_id). cluster_properties sums each cluster's cafés and new
        places. With the :cluster_marker slot, the browser draws each
        cluster as a copy of its HTML, filled from those properties:
        data-cluster-text sets a text, data-cluster-show shows an element
        only when its property is not zero, and each property is a CSS
        custom property, --cluster-cafes, for the pie. --%>
  <.geojson_layer
    id="scenario-clusters-places"
    map_id="scenario-clusters-map"
    type="circle"
    data={@places}
    promote_id="place_id"
    cluster
    cluster_properties={cluster_properties()}
    cluster_expand_on_click
    events={["layer:feature_clicked"]}
    cursor="pointer"
    paint={paint()}
  >
    <:cluster_marker :if={@drawn == "html"}>
      <div
        class="relative grid size-10 cursor-pointer place-items-center rounded-full shadow-[0_0_0_2px_#ffffff]"
        style={pie_style()}
        aria-label={gettext("{point_count} places, {cafes} cafés, {new} new")}
      >
        <span
          class="grid size-7 place-items-center rounded-full bg-white font-sans text-label font-bold text-map-ink"
          data-cluster-text="point_count_abbreviated"
        ></span>
        <span
          class="absolute -top-1 -right-1 grid h-4 min-w-4 place-items-center rounded-full px-1 font-sans text-[10px] leading-none font-bold text-white"
          style={"background-color: #{new_color()}"}
          data-cluster-show="new"
          data-cluster-text="new"
        ></span>
      </div>
    </:cluster_marker>
  </.geojson_layer>

  <%!-- Each cluster's count, from the layer's source: MapLibre gives a
        cluster point_count and point_count_abbreviated. --%>
  <.symbol_layer
    :if={@drawn == "paint"}
    id="scenario-clusters-counts"
    map_id="scenario-clusters-map"
    source_id="scenario-clusters-places-source"
    filter={["has", "point_count"]}
    layout={
      %{
        "text-field" => ["get", "point_count_abbreviated"],
        "text-font" => ["Noto Sans Bold"],
        "text-size" => 12,
        "text-allow-overlap" => true
      }
    }
    paint={%{"text-color" => "#ffffff"}}
  />

  <%!-- What the colours mean, from the palette the layer and the HTML read:
        it follows how the clusters are drawn. --%>
  <.legend
    id="scenario-clusters-legend"
    map_id="scenario-clusters-map"
    position="top-left"
    title={gettext("Places")}
    collapsible
  >
    <:item :for={{kind, color} <- kinds()} color={color} shape={:circle} label={kind_label(kind)} />
    <:item
      :if={@drawn == "paint"}
      color={cluster_color()}
      shape={:circle}
      label={gettext("A cluster")}
    />
    <:item :if={@drawn == "html"} label={gettext("A cluster: its cafés and shops")}>
      <span class="block size-3 rounded-full" style={pie_style_of(3, 5)}></span>
    </:item>
    <:item :if={@drawn == "html"} label={gettext("New places in a cluster")}>
      <span class="block size-3 rounded-full" style={"background-color: #{new_color()}"}></span>
    </:item>
  </.legend>

  <div class="grid gap-x-8 gap-y-4 border-t border-line px-4 py-4 lg:grid-cols-[1fr_auto]">
    <%!-- The places of the cluster clicked, as layer:cluster_leaves_loaded
          gives them, or the place clicked. --%>
    <div id="scenario-clusters-list" role="group" aria-labelledby="scenario-clusters-list-label">
      <p id="scenario-clusters-list-label" class="mb-2 text-label font-bold text-ink-subtle">
        {gettext("Places listed")}
        <span
          :if={@cluster}
          id="scenario-clusters-listing"
          class="ml-1.5 font-mono font-normal tabular-nums"
        >
          {listing(@cluster)}
        </span>
      </p>

      <p
        :if={@error}
        id="scenario-clusters-error"
        role="status"
        class="flex items-start gap-1.5 text-ui text-ink-muted"
      >
        <.icon name="hero-exclamation-circle-mini" class="mt-px size-4 shrink-0 text-danger" />
        <span>
          {gettext("The layer could not list that cluster:")}
          <span class="font-mono text-label">{@error}</span>
          {gettext("Click it again.")}
        </span>
      </p>

      <p :if={@listed == [] and !@error} class="text-ui text-ink-muted">
        {gettext("Click a cluster to list its places, or a place to list it alone.")}
      </p>

      <ol :if={@listed != []} class="grid gap-x-6 sm:grid-cols-2">
        <li
          :for={place <- @listed}
          id={"scenario-clusters-place-#{place.id}"}
          class="flex items-baseline justify-between gap-3 border-b border-line py-1.5 font-mono text-label"
        >
          <span class="text-ink">{place.id}</span>
          <span class="text-ink-subtle tabular-nums">{place.lng_lat}</span>
        </li>
      </ol>
    </div>

    <div class="space-y-4">
      <%!-- How the clusters are drawn: the layer's paint, or the slot. --%>
      <.example_group id="scenario-clusters-drawn" label={gettext("Clusters drawn by")}>
        <.example_button
          :for={drawn <- drawings()}
          id={"scenario-clusters-drawn-#{drawn}"}
          code
          pressed={@drawn == drawn}
          phx-click="drawn"
          phx-value-drawn={drawn}
        >
          {drawing_label(drawn)}
        </.example_button>
      </.example_group>

      <%!-- Paging: each page is one more layer:cluster_leaves, with offset. --%>
      <.example_group id="scenario-clusters-pages" label={gettext("Page through the cluster")}>
        <.example_button
          id="scenario-clusters-previous"
          phx-click="page"
          phx-value-to="previous"
          disabled={first_page?(@cluster)}
        >
          <.icon name="hero-chevron-left-mini" class="size-4" />
          {gettext("Previous")}
        </.example_button>
        <.example_button
          id="scenario-clusters-next"
          phx-click="page"
          phx-value-to="next"
          disabled={last_page?(@cluster)}
        >
          {gettext("Next")}
          <.icon name="hero-chevron-right-mini" class="size-4" />
        </.example_button>
      </.example_group>
    </div>
  </div>

  <div class="space-y-2 px-4 pb-4">
    <.example_note id="scenario-clusters-sample-data">
      {gettext(
        "Sample data: 400 places generated around five parts of Lisbon, with a fixed seed. They are not real places."
      )}
    </.example_note>
    <.example_note id="scenario-clusters-how" icon="hero-information-circle-micro">
      {gettext(
        "A click on a cluster zooms in to where it breaks apart, in the browser, and the server asks the layer for the places it held, ten at a time."
      )}
    </.example_note>
  </div>

  <%!-- The cluster clicked, and the request that asked for its places. --%>
  <.example_readout values={[
    drawn: @drawn,
    cluster_id: cluster_value(@cluster, :id),
    point_count: cluster_value(@cluster, :count),
    offset: cluster_value(@cluster, :offset),
    request: @request,
    listed: length(@listed)
  ]} />
</div>
lib/maplibrex_demo_web/scenarios/clusters_scenario.ex
defmodule MaplibrexDemoWeb.Scenarios.ClustersScenario do
  @moduledoc """
  Clustered places: 400 sample places around Lisbon, made up for the demo,
  drawn by one clustered GeoJSON circle layer, with each cluster's count
  drawn by a `<.symbol_layer>` over the layer's source.

    * A click on a cluster opens it: the camera moves to where MapLibre
      breaks it apart, in the browser (`cluster_expand_on_click`).
    * The same click pushes `layer:feature_clicked`, which names the
      cluster (`"cluster_id"`, `"point_count"`). The LiveView asks the layer
      for the cluster's places, ten at a time, with the push
      `layer:cluster_leaves`, and lists those the layer gives back in
      `layer:cluster_leaves_loaded`. Each request carries a `ref`, which the
      answer gives back, so that an answer to an earlier request is dropped.
    * A click on a single place lists it alone, from its feature.
    * The clusters are drawn by the layer's paint, or, with a
      `:cluster_marker` slot, as HTML of the page's own: the count, a badge
      of the new places it holds, and a pie of its cafés and shops, filled
      in the browser from each cluster's properties, which
      `cluster_properties` sums.

  The places are generated with a fixed seed, so every visit draws the same
  map. They are not real places.
  """
  use MaplibrexDemoWeb, :live_view

  import MaplibreX.Components
  import MaplibrexDemoWeb.Examples.ExampleComponents

  # Demo plumbing, not needed in an application: applies the page's locale
  # 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"

  @centre [-9.1460, 38.7340]
  @count 400

  # How many places a request asks for, and the page of the list.
  @limit 10

  # The palette, once: a café, a shop, and a cluster drawn by paint. The
  # layer's paint, the HTML clusters and the legend all read it.
  @kinds [{"cafe", "#7c5cd6"}, {"shop", "#0f8b8d"}]
  @cluster_color "#d9480f"
  @new_color "#c92a2a"

  # How the clusters are drawn: by the layer's paint, or as HTML.
  @drawings ~w(paint html)

  # Centre and spread, in degrees, of each part of Lisbon the sample places
  # gather around.
  @hotspots [
    {[-9.1420, 38.7260], 0.005},
    {[-9.1640, 38.7220], 0.004},
    {[-9.1200, 38.7420], 0.005},
    {[-9.1780, 38.7480], 0.005},
    {[-9.1420, 38.7560], 0.004}
  ]

  @impl true
  def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(cluster: nil, listed: [], request: 0, error: nil, map_error: nil)
      |> assign(:drawn, "paint")
      # The places, once: they never change, so LiveView never sends them again.
      |> assign(:places, sample_places())

    {:ok, socket}
  end

  # A click on a cluster names it: ask for its first places. The layer opens
  # the cluster in the browser by itself.
  @impl true
  def handle_event(
        "layer:feature_clicked",
        %{"cluster_id" => id, "point_count" => count},
        socket
      )
      when is_integer(id) and is_integer(count) do
    {:noreply, socket |> assign(:cluster, %{id: id, count: count, offset: 0}) |> ask()}
  end

  # A click on a single place carries it: list it alone.
  def handle_event("layer:feature_clicked", %{"feature" => place}, socket) do
    {:noreply, assign(socket, cluster: nil, listed: [row(place)], error: nil)}
  end

  # The answer to the last request: its places, or why there are none.
  # An answer to an earlier one carries another ref, and is dropped.
  def handle_event("layer:cluster_leaves_loaded", %{"ref" => ref} = answer, socket)
      when ref == socket.assigns.request do
    case answer do
      %{"features" => places} -> {:noreply, assign(socket, listed: Enum.map(places, &row/1))}
      %{"error" => error} -> {:noreply, assign(socket, listed: [], error: error)}
    end
  end

  def handle_event("layer:cluster_leaves_loaded", _stale, socket), do: {:noreply, socket}

  # Paging through the cluster: the next or the previous ten places.
  def handle_event("page", %{"to" => to}, %{assigns: %{cluster: %{} = cluster}} = socket) do
    offset =
      case to do
        "next" -> cluster.offset + @limit
        _previous -> cluster.offset - @limit
      end

    if offset >= 0 and offset < cluster.count do
      {:noreply, socket |> assign(:cluster, %{cluster | offset: offset}) |> ask()}
    else
      {:noreply, socket}
    end
  end

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

  # How the clusters are drawn. The layer keeps its source: only the slot
  # comes and goes.
  def handle_event("drawn", %{"drawn" => drawn}, socket) when drawn in @drawings do
    {:noreply, assign(socket, :drawn, drawn)}
  end

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

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

  # Asks the layer for a page of the cluster's places, under a new ref.
  defp ask(socket) do
    %{cluster: cluster, request: request} = socket.assigns

    socket
    |> assign(request: request + 1, error: nil)
    |> push_event("layer:cluster_leaves", %{
      layer_id: "scenario-clusters-places",
      cluster_id: cluster.id,
      limit: @limit,
      offset: cluster.offset,
      ref: request + 1
    })
  end

  # A place as the list shows it: its id and where MapLibre's clustering
  # index has it, which can differ from the data in the last decimals.
  defp row(%{"properties" => %{"place_id" => id}, "geometry" => %{"coordinates" => [lng, lat]}}) do
    %{id: id, lng_lat: "#{coordinate(lat)}, #{coordinate(lng)}"}
  end

  defp coordinate(value) when is_float(value), do: Float.round(value, 5)
  defp coordinate(value), do: value

  # "11–20 / 25": the places of the cluster listed, of how many.
  defp listing(%{offset: offset, count: count}) do
    "#{offset + 1}–#{min(offset + @limit, count)} / #{count}"
  end

  defp first_page?(cluster), do: cluster == nil or cluster.offset == 0
  defp last_page?(cluster), do: cluster == nil or cluster.offset + @limit >= cluster.count

  # Clusters are purple and grow with their count; single places are teal.
  defp paint do
    cluster? = ["has", "point_count"]

    %{
      "circle-color" => ["case", cluster?, @cluster_color, kind_color()],
      "circle-radius" => [
        "case",
        cluster?,
        ["step", ["get", "point_count"], 14, 10, 18, 50, 24],
        6
      ],
      "circle-stroke-color" => "#ffffff",
      "circle-stroke-width" => 2
    }
  end

  # ["match", ["get", "kind"], "cafe", "#7c5cd6", "shop", "#0f8b8d", ...]:
  # the last colour is for any other kind.
  defp kind_color do
    ["match", ["get", "kind"]] ++ Enum.flat_map(@kinds, &Tuple.to_list/1) ++ ["#63637a"]
  end

  # What each cluster sums of its places: its cafés and its new places.
  # Each is a property of the cluster, which the HTML reads.
  defp cluster_properties do
    %{
      "cafes" => ["+", ["case", ["==", ["get", "kind"], "cafe"], 1, 0]],
      "new" => ["+", ["case", ["get", "new"], 1, 0]]
    }
  end

  # The pie of a cluster drawn as HTML: its share of cafés, in the cafés'
  # colour, the rest in the shops', from the CSS custom properties the
  # browser sets on each cluster.
  defp pie_style do
    [{"cafe", cafe}, {"shop", shop}] = @kinds

    "--share: calc(var(--cluster-cafes) / var(--cluster-point-count) * 100%); " <>
      "background: conic-gradient(#{cafe} 0 var(--share), #{shop} var(--share) 100%)"
  end

  # The legend's swatch of a cluster: a pie of so many cafés in so many places.
  defp pie_style_of(cafes, places) do
    [{"cafe", cafe}, {"shop", shop}] = @kinds
    share = round(cafes / places * 100)
    "background: conic-gradient(#{cafe} 0 #{share}%, #{shop} #{share}% 100%)"
  end

  defp kind_label("cafe"), do: gettext("Café")
  defp kind_label("shop"), do: gettext("Shop")

  defp kinds, do: @kinds
  defp drawings, do: @drawings
  defp cluster_color, do: @cluster_color
  defp new_color, do: @new_color

  defp drawing_label("paint"), do: "paint"
  defp drawing_label("html"), do: ":cluster_marker"

  # Sample data, generated with a fixed seed: the same places on every visit.
  defp sample_places do
    hotspots = List.to_tuple(@hotspots)

    {features, _seed} =
      Enum.map_reduce(1..@count, :rand.seed_s(:exsss, 2027), fn i, seed ->
        {[lng, lat], spread} = elem(hotspots, rem(i, tuple_size(hotspots)))
        {dx, seed} = :rand.normal_s(seed)
        {dy, seed} = :rand.normal_s(seed)

        feature = %{
          "type" => "Feature",
          "geometry" => %{
            "type" => "Point",
            "coordinates" => [
              Float.round(lng + dx * spread, 5),
              Float.round(lat + dy * spread, 5)
            ]
          },
          "properties" => %{
            "place_id" => "P-" <> String.pad_leading("#{i}", 3, "0"),
            # About two in five places are cafés, by a hash of its number
            # (its hotspot is its number modulo 5), and one in seventeen is
            # new: the positions stay as the seed gives them.
            "kind" => if(:erlang.phash2({i, :kind}, 5) < 2, do: "cafe", else: "shop"),
            "new" => rem(i * 13, 17) == 0
          }
        }

        {feature, seed}
      end)

    %{"type" => "FeatureCollection", "features" => features}
  end

  defp centre, do: @centre

  defp cluster_value(nil, _key), do: "nil"
  defp cluster_value(cluster, key), do: Map.fetch!(cluster, key)
end