Zonas de reparto
Datos de ejemploZonas de reparto de ejemplo dibujadas por su contorno, que se eligen en una lista junto al mapa o con un clic dentro de ellas, se iluminan bajo el puntero y desde la lista, con alertas activadas desde el servidor.
Zonas
Alerta en la zona seleccionada
Datos de ejemplo: seis zonas de reparto inventadas alrededor de Valencia, dibujadas para este escenario.
Cada zona se dibuja por su contorno. Su relleno no dibuja nada, pero responde a un clic en cualquier punto de la zona; el contorno también ilumina la zona desde unos píxeles fuera de ella, donde un clic no selecciona nada. Señala una zona o su fila: las dos se iluminan. Las pantallas táctiles no tienen hover.
- @selected
- —
- @alerts
- —
<div id="zones-scenario">
<.example_frame error={@map_error} error_id="scenario-zones-map-error" tall>
<.map
id="scenario-zones-map"
center={centre()}
zoom={12.8}
style={basemap(@theme)}
events={["map:error"]}
class="h-full w-full"
/>
</.example_frame>
<.navigation_control id="scenario-zones-navigation" map_id="scenario-zones-map" />
<%!-- The zones' areas: a fill that draws nothing at rest, yet answers a
click anywhere inside a zone. Each zone's id is its code
(promote_id); feature_state gives the selected one selected: true,
and hover gives the one under the pointer hover: true. label_points
keeps a point well inside each zone, in "scenario-zones-areas-labels",
for its name. --%>
<.geojson_layer
id="scenario-zones-areas"
map_id="scenario-zones-map"
type="fill"
data={@zones}
promote_id="code"
label_points
feature_state={selection(@selected)}
hover
events={["layer:feature_clicked"]}
cursor="pointer"
paint={area_paint()}
/>
<%!-- The outlines: a line layer over the areas' source, which reads the
state set on it. hover lights a zone within 8 px of its outline too
(hit_width), where a click, outside the fill, selects nothing. --%>
<.line_layer
id="scenario-zones-outlines"
map_id="scenario-zones-map"
source_id="scenario-zones-areas-source"
hover
hit_width={8}
layout={%{"line-join" => "round"}}
paint={outline_paint()}
/>
<%!-- Each zone's name, once, from its label point, in the page's ink. --%>
<.symbol_layer
id="scenario-zones-names"
map_id="scenario-zones-map"
source_id="scenario-zones-areas-labels"
layout={
%{
"text-field" => ["get", "name"],
"text-font" => ["Noto Sans Bold"],
"text-size" => 13
}
}
paint={name_paint(@theme)}
/>
<%!-- What the outlines' colours mean, from their palette, and the names,
which the legend hides and shows. --%>
<.legend
id="scenario-zones-legend"
map_id="scenario-zones-map"
position="top-left"
title={gettext("Zones")}
collapsible
>
<:item :for={{color, label} <- outline_entries()} color={color} shape={:line} label={label} />
<:item label={gettext("Zone names")} layers={["scenario-zones-names"]}>
<span class="font-sans text-[11px] leading-none font-bold">Aa</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 list: a row selects its zone; HoverRow lights the zone as the
pointer enters the row (GeoJSONLayer.hover/2) and takes it off as
it leaves (unhover/1); HoveredRows lights the row of the zone under
the pointer, from maplibrex:feature_hovered. --%>
<div
id="scenario-zones-list"
phx-hook="HoveredRows"
data-layers="scenario-zones-areas scenario-zones-outlines"
>
<.example_group id="scenario-zones-rows" label={gettext("Zones")}>
<.example_button
:for={%{"properties" => %{"code" => code}} <- @zones["features"]}
id={"scenario-zones-row-#{code}"}
code
pressed={@selected == code}
phx-click="select"
phx-value-code={code}
phx-hook="HoverRow"
data-feature-id={code}
data-hover={GeoJSONLayer.hover("scenario-zones-areas", code)}
data-unhover={GeoJSONLayer.unhover("scenario-zones-areas")}
>
{code}
<span :if={code in @alerts} data-alert class="inline-flex text-danger">
<.icon name="hero-exclamation-triangle-micro" class="size-4" />
<span class="sr-only">{gettext("alert")}</span>
</span>
</.example_button>
</.example_group>
</div>
<%!-- An alert on the selected zone: pushed as layer:set_feature_state. --%>
<.example_group id="scenario-zones-alerts" label={gettext("Alert on the selected zone")}>
<.example_button
id="scenario-zones-raise"
phx-click="raise_alert"
disabled={!@selected or @selected in @alerts}
>
{gettext("Raise")}
</.example_button>
<.example_button
id="scenario-zones-clear"
phx-click="clear_alert"
disabled={@selected not in @alerts}
>
{gettext("Clear")}
</.example_button>
</.example_group>
</div>
<div class="space-y-2 px-4 pb-4">
<.example_note id="scenario-zones-sample-data">
{gettext(
"Sample data: six made-up delivery zones around Valencia, drawn for this scenario."
)}
</.example_note>
<.example_note id="scenario-zones-how" icon="hero-information-circle-micro">
{gettext(
"Each zone is drawn by its outline. Its fill draws nothing, yet answers a click anywhere inside the zone; the outline also lights the zone from a few pixels outside it, where a click selects nothing. Point at a zone or at its row: both light up. Touch screens have no hover."
)}
</.example_note>
</div>
<%!-- feature_state follows selected; the pushes follow alerts. --%>
<.example_readout values={[selected: @selected || "—", alerts: alerts_label(@alerts)]} />
</div>
defmodule MaplibrexDemoWeb.Scenarios.ZonesScenario do
@moduledoc """
Delivery zones: six sample zones around Valencia, made up for the demo,
drawn by their outline and listed beside the map.
The zones are one GeoJSON fill layer whose fill draws nothing at rest
(`fill-opacity` 0) yet answers the pointer in the whole of each zone,
and a `<.line_layer>` over its source that draws their outlines, as the
library documents hollow polygons. Each zone's id is its code
(`promote_id`).
* The zone selected, from its row or with a click inside it, has the
feature state `selected`, given by the layer's `feature_state`.
* An alert is raised and cleared on the selected zone with the push
`layer:set_feature_state`, which sends that zone's state alone.
* `hover` on both layers lights the zone under the pointer, inside it
or within the outline's `hit_width`; a row lights its zone from
outside the map with `GeoJSONLayer.hover/2` and `unhover/1`, and the
row of the zone under the pointer lights up, from the
`maplibrex:feature_hovered` event the window hears. Both run in the
browser (the `HoverRow` and `HoveredRows` hooks of
`assets/js/hover_rows.js`), with nothing sent to the server.
* Each zone's name is drawn once, well inside it, by a symbol layer
over the areas' label points (`label_points`, `"<id>-labels"`).
* A legend says what the outlines' colours mean: the outlines' paint
and the legend's lines come from one palette.
"""
use MaplibrexDemoWeb, :live_view
import MaplibreX.Components
import MaplibrexDemoWeb.Examples.ExampleComponents
alias MaplibreX.Components.GeoJSONLayer
# 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 [-0.3763, 39.4699]
# Metres per degree of longitude and of latitude around the centre.
@east_metres 111_320 * :math.cos(39.4699 * :math.pi() / 180)
@north_metres 110_574
# Sample data: each zone's code and its centre, in metres east and north
# of the centre of Valencia. A zone is a hexagon about 1.6 km across,
# made irregular by the scale of each corner.
@zones [
{"Z-1", {-1900, 950}},
{"Z-2", {0, 1100}},
{"Z-3", {1900, 950}},
{"Z-4", {-1900, -950}},
{"Z-5", {0, -1100}},
{"Z-6", {1900, -950}}
]
@radius 800
@corners [1.0, 0.88, 1.06, 0.94, 1.0, 0.9]
# The outlines' palette, once: a zone at rest, one selected or under the
# pointer, one with an alert. The outline's paint and the legend's lines
# both read it.
@outline_colors %{zone: "#0f8b8d", lit: "#7c5cd6", alert: "#c92a2a"}
# The names' ink and halo, of the page's theme.
defp ink("dark"), do: "#e8e9f1"
defp ink("light"), do: "#1f2330"
defp halo("dark"), do: "#12141b"
defp halo("light"), do: "#ffffff"
@impl true
def mount(_params, _session, socket) do
socket =
socket
|> assign(selected: nil, alerts: MapSet.new(), map_error: nil)
# The zones, once: they never change, so LiveView never sends them again.
|> assign(:zones, feature_collection())
{:ok, socket}
end
# A row selects its zone, or, when it is selected, takes the selection
# off: the layer's feature_state follows @selected.
@impl true
def handle_event("select", %{"code" => code}, socket) do
cond do
code == socket.assigns.selected -> {:noreply, assign(socket, :selected, nil)}
code in codes() -> {:noreply, assign(socket, :selected, code)}
true -> {:noreply, socket}
end
end
# A click anywhere inside a zone carries its feature, whose code is its id.
def handle_event("layer:feature_clicked", %{"feature" => feature}, socket) do
code = feature["properties"]["code"]
{:noreply, if(code in codes(), do: assign(socket, :selected, code), else: socket)}
end
# An alert on the selected zone goes to the layer as a push of that zone's
# state alone; a nil value takes the key off. @alerts keeps them for the
# rows and the buttons.
def handle_event("raise_alert", _params, socket) do
%{selected: code, alerts: alerts} = socket.assigns
if code && code not in alerts do
{:noreply,
socket
|> assign(:alerts, MapSet.put(alerts, code))
|> push_event("layer:set_feature_state", %{
layer_id: "scenario-zones-areas",
states: %{code => %{alert: true}}
})}
else
{:noreply, socket}
end
end
def handle_event("clear_alert", _params, socket) do
%{selected: code, alerts: alerts} = socket.assigns
if code in alerts do
{:noreply,
socket
|> assign(:alerts, MapSet.delete(alerts, code))
|> push_event("layer:set_feature_state", %{
layer_id: "scenario-zones-areas",
states: %{code => %{alert: nil}}
})}
else
{:noreply, socket}
end
end
def handle_event("map:error", %{"error" => message}, socket) do
{:noreply, assign(socket, :map_error, message)}
end
# The selected zone as feature state: its code to `selected: true`. An
# empty map when none is selected, so the layer takes the state off.
defp selection(nil), do: %{}
defp selection(code), do: %{code => %{selected: true}}
# The fill draws nothing but the selected zone's tint: at fill-opacity 0
# it still answers the pointer in the whole zone, as MapLibre looks at no
# opacity when it finds the features under the pointer.
defp area_paint do
%{
"fill-color" => "#7c5cd6",
"fill-opacity" => ["case", ["boolean", ["feature-state", "selected"], false], 0.2, 0]
}
end
# The outline reads the state the layers set on the zones' source: red
# for an alert, purple while the zone is selected or under the pointer,
# teal otherwise.
defp outline_paint do
lit = [
"any",
["boolean", ["feature-state", "selected"], false],
["boolean", ["feature-state", "hover"], false]
]
%{
"line-color" => [
"case",
["boolean", ["feature-state", "alert"], false],
@outline_colors.alert,
lit,
@outline_colors.lit,
@outline_colors.zone
],
"line-width" => ["case", lit, 4, 2]
}
end
# What the legend says of each colour, in its order.
defp outline_entries do
[
{@outline_colors.zone, gettext("Zone")},
{@outline_colors.lit, gettext("Selected or under the pointer")},
{@outline_colors.alert, gettext("Alert")}
]
end
# The names: the paint follows the page's theme, the halo its ground.
defp name_paint(theme) do
%{"text-color" => ink(theme), "text-halo-color" => halo(theme), "text-halo-width" => 1.5}
end
defp feature_collection do
%{"type" => "FeatureCollection", "features" => Enum.with_index(@zones, &feature/2)}
end
defp zone_name("Z-1"), do: gettext("North-west")
defp zone_name("Z-2"), do: gettext("North")
defp zone_name("Z-3"), do: gettext("North-east")
defp zone_name("Z-4"), do: gettext("South-west")
defp zone_name("Z-5"), do: gettext("South")
defp zone_name("Z-6"), do: gettext("South-east")
# A hexagon around the zone's centre, each corner at its own scale of the
# radius, the scales turned by the zone's place in the list.
defp feature({code, {east, north}}, index) do
scales = Enum.slice(@corners ++ @corners, index, 6)
[lng, lat] = @centre
ring =
for {scale, corner} <- Enum.with_index(scales) do
angle = corner * :math.pi() / 3
x = east + @radius * scale * :math.cos(angle)
y = north + @radius * scale * :math.sin(angle)
[Float.round(lng + x / @east_metres, 6), Float.round(lat + y / @north_metres, 6)]
end
%{
"type" => "Feature",
"geometry" => %{"type" => "Polygon", "coordinates" => [ring ++ [hd(ring)]]},
"properties" => %{"code" => code, "name" => zone_name(code)}
}
end
defp codes, do: Enum.map(@zones, &elem(&1, 0))
defp centre, do: @centre
defp alerts_label(alerts) do
if Enum.empty?(alerts), do: "—", else: alerts |> Enum.sort() |> Enum.join(", ")
end
end