Audience dashboard
Viewers by region as cards on the map, arcs from the studio, and a period switch.
Map and code
All viewers
Loading the map…
The map couldn't load.
All viewers
Loading the map…
The map couldn't load.
All viewers
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
All viewers
Loading the map…
The map couldn't load.
All viewers
Loading the map…
The map couldn't load.
All viewers
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
These maps come from Google Maps and OpenFreeMap, which see your IP address. They stay off until you say so, once for the whole site. What loading the maps sends
Fetches audience.jsonStyled by audience.css
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- A streaming service's viewers by region: each region a card on the map, its top genre and
its viewers in the period chosen, an arc to it from the studio, and the list beside the map
with each region's share; the select above swaps the period, the total adds them up. -->
<!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../../styles/audience.css">
<style>
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-maplibre-map { height: 36rem; }
#audience-maplibre-map > .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<p><label for="audience-maplibre-period">Period</label> <select id="audience-maplibre-period">
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y" selected>Last year</option>
</select></p>
<maplace-map id="audience-maplibre-map" list="maplibre-audience-regions" list-heading="By region"></maplace-map>
<p>All viewers <output id="audience-maplibre-total"></output></p>
<script>
// The list's entries, the page's own: a view defined as the page is read, so the map finds it
// when it opens; the module below gives the map its regions.
{
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const span = (className, ...children) => {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
};
// A region in the list: its name and viewers, its genre and share, and the share as a bar on a track.
const regionEntry = ({ location }) => {
const { genre, viewers, share } = location.data;
const bar = span("audience-bar");
bar.style.width = `${share}%`;
const track = span("audience-track", bar);
track.setAttribute("aria-hidden", "true");
const entry = span(
"audience-entry",
span("audience-entry-title", location.title),
span("audience-entry-viewers", compact.format(viewers)),
span("audience-entry-genre", genre),
span("audience-entry-share", `${share}%`),
track,
);
entry.dataset.genre = genre;
return entry;
};
Maplace.defineListView("maplibre-audience-regions", (maplace, { options }) =>
Maplace.createListView(maplace, { ...options, render: regionEntry }));
}
</script>
<script type="module">
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
const span = (className, ...children) => {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
};
// A region on the map: its genre's letter, the genre, and its viewers.
const regionCard = ({ data }) => {
const card = span(
"audience-card",
span("audience-badge", data.genre.charAt(0)),
span("audience-card-text", span("audience-genre", data.genre), span("audience-viewers", compact.format(data.viewers))),
);
card.dataset.genre = data.genre;
return card;
};
const { maplace } = document.getElementById("audience-maplibre-map");
// Every region in view, with room at the edges for the cards.
maplace.fitAll({ padding: 64 });
const audience = await fetch("/examples/data/audience.json").then((response) => response.json());
// Every region's viewers in a period, added up.
const totalFor = (period) => audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
// Each region with its figures for a period, an arc to it from the studio, and the studio.
const locationsFor = (period) => {
const { studio, regions } = audience;
const total = totalFor(period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
icon: regionCard,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(({ id, title, lat, lng }) => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [{ lat: studio.lat, lng: studio.lng }, { lat, lng }],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
})),
{ id: "studio", ...studio, listed: false },
];
};
const total = document.getElementById("audience-maplibre-total");
const period = document.getElementById("audience-maplibre-period");
const showPeriod = () => {
maplace.setLocations(locationsFor(period.value));
total.value = whole.format(totalFor(period.value));
};
showPeriod();
period.addEventListener("change", showPeriod);
// A click on an arc selects its region, as a click on the region's card does.
maplace.on("selectionChange", ({ id }) => {
if (id?.endsWith("-arc")) maplace.select(id.replace(/-arc$/, ""));
});
</script><!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- A streaming service's viewers by region: each region a card on the map, its top genre and
its viewers in the period chosen, an arc to it from the studio, and the list beside the map
with each region's share; the select above swaps the period, the total adds them up. -->
<!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../styles/audience.css">
<style>
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-map { height: 36rem; }
#audience-map > .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<p><label for="audience-period">Period</label> <select id="audience-period">
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y" selected>Last year</option>
</select></p>
<maplace-map id="audience-map" api-key="YOUR_KEY" list="audience-regions" list-heading="By region"></maplace-map>
<p>All viewers <output id="audience-total"></output></p>
<script>
// The list's entries, the page's own: a view defined as the page is read, so the map finds it
// when it opens; the module below gives the map its regions.
{
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const span = (className, ...children) => {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
};
// A region in the list: its name and viewers, its genre and share, and the share as a bar on a track.
const regionEntry = ({ location }) => {
const { genre, viewers, share } = location.data;
const bar = span("audience-bar");
bar.style.width = `${share}%`;
const track = span("audience-track", bar);
track.setAttribute("aria-hidden", "true");
const entry = span(
"audience-entry",
span("audience-entry-title", location.title),
span("audience-entry-viewers", compact.format(viewers)),
span("audience-entry-genre", genre),
span("audience-entry-share", `${share}%`),
track,
);
entry.dataset.genre = genre;
return entry;
};
Maplace.defineListView("audience-regions", (maplace, { options }) =>
Maplace.createListView(maplace, { ...options, render: regionEntry }));
}
</script>
<script type="module">
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
const span = (className, ...children) => {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
};
// A region on the map: its genre's letter, the genre, and its viewers.
const regionCard = ({ data }) => {
const card = span(
"audience-card",
span("audience-badge", data.genre.charAt(0)),
span("audience-card-text", span("audience-genre", data.genre), span("audience-viewers", compact.format(data.viewers))),
);
card.dataset.genre = data.genre;
return card;
};
const { maplace } = document.getElementById("audience-map");
// Every region in view, with room at the edges for the cards.
maplace.fitAll({ padding: 64 });
const audience = await fetch("/examples/data/audience.json").then((response) => response.json());
// Every region's viewers in a period, added up.
const totalFor = (period) => audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
// Each region with its figures for a period, an arc to it from the studio, and the studio.
const locationsFor = (period) => {
const { studio, regions } = audience;
const total = totalFor(period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
icon: regionCard,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(({ id, title, lat, lng }) => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [{ lat: studio.lat, lng: studio.lng }, { lat, lng }],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
})),
{ id: "studio", ...studio, listed: false },
];
};
const total = document.getElementById("audience-total");
const period = document.getElementById("audience-period");
const showPeriod = () => {
maplace.setLocations(locationsFor(period.value));
total.value = whole.format(totalFor(period.value));
};
showPeriod();
period.addEventListener("change", showPeriod);
// A click on an arc selects its region, as a click on the region's card does.
maplace.on("selectionChange", ({ id }) => {
if (id?.endsWith("-arc")) maplace.select(id.replace(/-arc$/, ""));
});
</script><!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, what the map and its list mount on, and the map made with Maplace. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../../styles/audience.css">
<style>
#audience-maplibre-script-map-and-list { display: flex; height: 24rem; }
#audience-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
#audience-maplibre-script-list { display: contents; }
#audience-maplibre-script-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-maplibre-script-map-and-list { flex-direction: column; height: 36rem; }
#audience-maplibre-script-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<p><label for="audience-maplibre-script-period">Period</label> <select id="audience-maplibre-script-period">
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y" selected>Last year</option>
</select></p>
<div id="audience-maplibre-script-map-and-list">
<div id="audience-maplibre-script-map"></div>
<div id="audience-maplibre-script-list"></div>
</div>
<p>All viewers <output id="audience-maplibre-script-total"></output></p>
<script type="module">
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
const span = (className, ...children) => {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
};
// A region on the map: its genre's letter, the genre, and its viewers.
const regionCard = ({ data }) => {
const card = span(
"audience-card",
span("audience-badge", data.genre.charAt(0)),
span("audience-card-text", span("audience-genre", data.genre), span("audience-viewers", compact.format(data.viewers))),
);
card.dataset.genre = data.genre;
return card;
};
// A region in the list: its name and viewers, its genre and share, and the share as a bar on a track.
const regionEntry = ({ location }) => {
const { genre, viewers, share } = location.data;
const bar = span("audience-bar");
bar.style.width = `${share}%`;
const track = span("audience-track", bar);
track.setAttribute("aria-hidden", "true");
const entry = span(
"audience-entry",
span("audience-entry-title", location.title),
span("audience-entry-viewers", compact.format(viewers)),
span("audience-entry-genre", genre),
span("audience-entry-share", `${share}%`),
track,
);
entry.dataset.genre = genre;
return entry;
};
const maplace = Maplace.createMapLibreMap("#audience-maplibre-script-map", {
// Every region in view, with room at the edges for the cards.
view: { kind: "fit-all", padding: 64 },
list: { container: "#audience-maplibre-script-list", heading: "By region", render: regionEntry },
});
const audience = await fetch("/examples/data/audience.json").then((response) => response.json());
// Every region's viewers in a period, added up.
const totalFor = (period) => audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
// Each region with its figures for a period, an arc to it from the studio, and the studio.
const locationsFor = (period) => {
const { studio, regions } = audience;
const total = totalFor(period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
icon: regionCard,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(({ id, title, lat, lng }) => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [{ lat: studio.lat, lng: studio.lng }, { lat, lng }],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
})),
{ id: "studio", ...studio, listed: false },
];
};
const total = document.getElementById("audience-maplibre-script-total");
const period = document.getElementById("audience-maplibre-script-period");
const showPeriod = () => {
maplace.setLocations(locationsFor(period.value));
total.value = whole.format(totalFor(period.value));
};
showPeriod();
period.addEventListener("change", showPeriod);
// A click on an arc selects its region, as a click on the region's card does.
maplace.on("selectionChange", ({ id }) => {
if (id?.endsWith("-arc")) maplace.select(id.replace(/-arc$/, ""));
});
</script><!doctype html>
<!-- A page of your own script: the CDN script, what the map and its list mount on, and the map made with Maplace, which adds Maps JS with your key. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../styles/audience.css">
<style>
#audience-script-map-and-list { display: flex; height: 24rem; }
#audience-script-map { flex: 1 1 auto; min-width: 0; }
#audience-script-list { display: contents; }
#audience-script-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-script-map-and-list { flex-direction: column; height: 36rem; }
#audience-script-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<p><label for="audience-script-period">Period</label> <select id="audience-script-period">
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y" selected>Last year</option>
</select></p>
<div id="audience-script-map-and-list">
<div id="audience-script-map"></div>
<div id="audience-script-list"></div>
</div>
<p>All viewers <output id="audience-script-total"></output></p>
<script type="module">
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
const span = (className, ...children) => {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
};
// A region on the map: its genre's letter, the genre, and its viewers.
const regionCard = ({ data }) => {
const card = span(
"audience-card",
span("audience-badge", data.genre.charAt(0)),
span("audience-card-text", span("audience-genre", data.genre), span("audience-viewers", compact.format(data.viewers))),
);
card.dataset.genre = data.genre;
return card;
};
// A region in the list: its name and viewers, its genre and share, and the share as a bar on a track.
const regionEntry = ({ location }) => {
const { genre, viewers, share } = location.data;
const bar = span("audience-bar");
bar.style.width = `${share}%`;
const track = span("audience-track", bar);
track.setAttribute("aria-hidden", "true");
const entry = span(
"audience-entry",
span("audience-entry-title", location.title),
span("audience-entry-viewers", compact.format(viewers)),
span("audience-entry-genre", genre),
span("audience-entry-share", `${share}%`),
track,
);
entry.dataset.genre = genre;
return entry;
};
const maplace = Maplace.createGoogleMap("#audience-script-map", {
apiKey: "YOUR_KEY",
// Every region in view, with room at the edges for the cards.
view: { kind: "fit-all", padding: 64 },
list: { container: "#audience-script-list", heading: "By region", render: regionEntry },
});
const audience = await fetch("/examples/data/audience.json").then((response) => response.json());
// Every region's viewers in a period, added up.
const totalFor = (period) => audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
// Each region with its figures for a period, an arc to it from the studio, and the studio.
const locationsFor = (period) => {
const { studio, regions } = audience;
const total = totalFor(period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
icon: regionCard,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(({ id, title, lat, lng }) => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [{ lat: studio.lat, lng: studio.lng }, { lat, lng }],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
})),
{ id: "studio", ...studio, listed: false },
];
};
const total = document.getElementById("audience-script-total");
const period = document.getElementById("audience-script-period");
const showPeriod = () => {
maplace.setLocations(locationsFor(period.value));
total.value = whole.format(totalFor(period.value));
};
showPeriod();
period.addEventListener("change", showPeriod);
// A click on an arc selects its region, as a click on the region's card does.
maplace.on("selectionChange", ({ id }) => {
if (id?.endsWith("-arc")) maplace.select(id.replace(/-arc$/, ""));
});
</script><!doctype html>
<!-- The page vanilla.ts runs on: what the module mounts on, and the module, which brings maplibre-gl and its stylesheet. -->
<!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../../styles/audience.css">
<style>
#audience-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
#audience-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
#audience-maplibre-vanilla-list { display: contents; }
#audience-maplibre-vanilla-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-maplibre-vanilla-map-and-list { flex-direction: column; height: 36rem; }
#audience-maplibre-vanilla-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<p><label for="audience-maplibre-vanilla-period">Period</label> <select id="audience-maplibre-vanilla-period">
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y" selected>Last year</option>
</select></p>
<div id="audience-maplibre-vanilla-map-and-list">
<div id="audience-maplibre-vanilla-map"></div>
<div id="audience-maplibre-vanilla-list"></div>
</div>
<p>All viewers <output id="audience-maplibre-vanilla-total"></output></p>
<script type="module" src="./vanilla.ts"></script>import "maplibre-gl/dist/maplibre-gl.css";
import type { ListEntry, Location } from "@maplacejs/maplace";
import { createMapLibreMap } from "@maplacejs/maplace/maplibre";
type Period = "1M" | "3M" | "1Y";
/** A region as the file has it: its top genre, and its viewers in each period. */
interface RegionRow {
readonly id: string;
readonly title: string;
readonly lat: number;
readonly lng: number;
readonly genre: string;
readonly viewers: Readonly<Record<Period, number>>;
}
/** The file: the studio the arcs leave from, and the regions. */
interface AudienceFile {
readonly studio: { readonly title: string; readonly lat: number; readonly lng: number };
readonly regions: readonly RegionRow[];
}
/** What a region's card and entry show for the period chosen. */
interface RegionFigures {
readonly genre: string;
readonly viewers: number;
readonly share: number;
}
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
function span(className: string, ...children: (Node | string)[]): HTMLSpanElement {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
}
/** A region on the map: its genre's letter, the genre, and its viewers. */
function regionCard({ data }: Location<RegionFigures>): HTMLElement {
const genre = data?.genre ?? "";
const card = span(
"audience-card",
span("audience-badge", genre.charAt(0)),
span(
"audience-card-text",
span("audience-genre", genre),
span("audience-viewers", compact.format(data?.viewers ?? 0)),
),
);
card.dataset.genre = genre;
return card;
}
/** A region in the list: its name and viewers, its genre and share, and the share as a bar on a track. */
function regionEntry({ location }: ListEntry<RegionFigures>): Node {
const { genre = "", viewers = 0, share = 0 } = location.data ?? {};
const bar = span("audience-bar");
bar.style.width = `${share}%`;
const track = span("audience-track", bar);
track.setAttribute("aria-hidden", "true");
const entry = span(
"audience-entry",
span("audience-entry-title", location.title ?? ""),
span("audience-entry-viewers", compact.format(viewers)),
span("audience-entry-genre", genre),
span("audience-entry-share", `${share}%`),
track,
);
entry.dataset.genre = genre;
return entry;
}
const maplace = createMapLibreMap<RegionFigures>("#audience-maplibre-vanilla-map", {
// Every region in view, with room at the edges for the cards.
view: { kind: "fit-all", padding: 64 },
list: { container: "#audience-maplibre-vanilla-list", heading: "By region", render: regionEntry },
});
const audience: AudienceFile = await (await fetch("/examples/data/audience.json")).json();
/** Every region's viewers in `period`, added up. */
function totalFor(period: Period): number {
return audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
}
/** Each region with its figures for `period`, an arc to it from the studio, and the studio. */
function locationsFor(period: Period): Location<RegionFigures>[] {
const { studio, regions } = audience;
const total = totalFor(period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
icon: regionCard,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(
({ id, title, lat, lng }): Location<RegionFigures> => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [
{ lat: studio.lat, lng: studio.lng },
{ lat, lng },
],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
}),
),
{ id: "studio", ...studio, listed: false },
];
}
const total = document.querySelector<HTMLOutputElement>("#audience-maplibre-vanilla-total");
const period = document.querySelector<HTMLSelectElement>("#audience-maplibre-vanilla-period");
function showPeriod(): void {
const chosen = (period?.value ?? "1Y") as Period;
maplace.setLocations(locationsFor(chosen));
if (total) total.value = whole.format(totalFor(chosen));
}
showPeriod();
period?.addEventListener("change", showPeriod);
// A click on an arc selects its region, as a click on the region's card does.
maplace.on("selectionChange", ({ id }) => {
if (id?.endsWith("-arc")) maplace.select(id.replace(/-arc$/, ""));
});<!doctype html>
<!-- The page vanilla.ts runs on: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->Google's bootstrap loader, with your API key: from Google's docs
<script>
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "YOUR_KEY",
v: "weekly",
});
</script><!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../styles/audience.css">
<style>
#audience-vanilla-map-and-list { display: flex; height: 24rem; }
#audience-vanilla-map { flex: 1 1 auto; min-width: 0; }
#audience-vanilla-list { display: contents; }
#audience-vanilla-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-vanilla-map-and-list { flex-direction: column; height: 36rem; }
#audience-vanilla-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<p><label for="audience-vanilla-period">Period</label> <select id="audience-vanilla-period">
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y" selected>Last year</option>
</select></p>
<div id="audience-vanilla-map-and-list">
<div id="audience-vanilla-map"></div>
<div id="audience-vanilla-list"></div>
</div>
<p>All viewers <output id="audience-vanilla-total"></output></p>
<script type="module" src="./vanilla.ts"></script>import type { ListEntry, Location } from "@maplacejs/maplace";
import { createGoogleMap } from "@maplacejs/maplace/google";
type Period = "1M" | "3M" | "1Y";
/** A region as the file has it: its top genre, and its viewers in each period. */
interface RegionRow {
readonly id: string;
readonly title: string;
readonly lat: number;
readonly lng: number;
readonly genre: string;
readonly viewers: Readonly<Record<Period, number>>;
}
/** The file: the studio the arcs leave from, and the regions. */
interface AudienceFile {
readonly studio: { readonly title: string; readonly lat: number; readonly lng: number };
readonly regions: readonly RegionRow[];
}
/** What a region's card and entry show for the period chosen. */
interface RegionFigures {
readonly genre: string;
readonly viewers: number;
readonly share: number;
}
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
function span(className: string, ...children: (Node | string)[]): HTMLSpanElement {
const element = document.createElement("span");
element.className = className;
element.append(...children);
return element;
}
/** A region on the map: its genre's letter, the genre, and its viewers. */
function regionCard({ data }: Location<RegionFigures>): HTMLElement {
const genre = data?.genre ?? "";
const card = span(
"audience-card",
span("audience-badge", genre.charAt(0)),
span(
"audience-card-text",
span("audience-genre", genre),
span("audience-viewers", compact.format(data?.viewers ?? 0)),
),
);
card.dataset.genre = genre;
return card;
}
/** A region in the list: its name and viewers, its genre and share, and the share as a bar on a track. */
function regionEntry({ location }: ListEntry<RegionFigures>): Node {
const { genre = "", viewers = 0, share = 0 } = location.data ?? {};
const bar = span("audience-bar");
bar.style.width = `${share}%`;
const track = span("audience-track", bar);
track.setAttribute("aria-hidden", "true");
const entry = span(
"audience-entry",
span("audience-entry-title", location.title ?? ""),
span("audience-entry-viewers", compact.format(viewers)),
span("audience-entry-genre", genre),
span("audience-entry-share", `${share}%`),
track,
);
entry.dataset.genre = genre;
return entry;
}
const maplace = createGoogleMap<RegionFigures>("#audience-vanilla-map", {
// Every region in view, with room at the edges for the cards.
view: { kind: "fit-all", padding: 64 },
list: { container: "#audience-vanilla-list", heading: "By region", render: regionEntry },
});
const audience: AudienceFile = await (await fetch("/examples/data/audience.json")).json();
/** Every region's viewers in `period`, added up. */
function totalFor(period: Period): number {
return audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
}
/** Each region with its figures for `period`, an arc to it from the studio, and the studio. */
function locationsFor(period: Period): Location<RegionFigures>[] {
const { studio, regions } = audience;
const total = totalFor(period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
icon: regionCard,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(
({ id, title, lat, lng }): Location<RegionFigures> => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [
{ lat: studio.lat, lng: studio.lng },
{ lat, lng },
],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
}),
),
{ id: "studio", ...studio, listed: false },
];
}
const total = document.querySelector<HTMLOutputElement>("#audience-vanilla-total");
const period = document.querySelector<HTMLSelectElement>("#audience-vanilla-period");
function showPeriod(): void {
const chosen = (period?.value ?? "1Y") as Period;
maplace.setLocations(locationsFor(chosen));
if (total) total.value = whole.format(totalFor(chosen));
}
showPeriod();
period?.addEventListener("change", showPeriod);
// A click on an arc selects its region, as a click on the region's card does.
maplace.on("selectionChange", ({ id }) => {
if (id?.endsWith("-arc")) maplace.select(id.replace(/-arc$/, ""));
});<!doctype html>
<!-- The page react.tsx renders into: what the module mounts on, and the module, which brings maplibre-gl and its stylesheet. -->
<!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../../styles/audience.css">
<style>
#audience-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
#audience-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
#audience-maplibre-react-root .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-maplibre-react-root .map-and-list { flex-direction: column; height: 36rem; }
#audience-maplibre-react-root .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="audience-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>import "maplibre-gl/dist/maplibre-gl.css";
import type { ListEntry, Location } from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
type Period = "1M" | "3M" | "1Y";
/** A region as the file has it: its top genre, and its viewers in each period. */
interface RegionRow {
readonly id: string;
readonly title: string;
readonly lat: number;
readonly lng: number;
readonly genre: string;
readonly viewers: Readonly<Record<Period, number>>;
}
/** The file: the studio the arcs leave from, and the regions. */
interface AudienceFile {
readonly studio: { readonly title: string; readonly lat: number; readonly lng: number };
readonly regions: readonly RegionRow[];
}
/** What a region's card and entry show for the period chosen. */
interface RegionFigures {
readonly genre: string;
readonly viewers: number;
readonly share: number;
}
/** Every region in view, with room at the edges for the cards. */
const FIRST_VIEW = { kind: "fit-all", padding: 64 } as const;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
/** Every region's viewers in `period`, added up. */
function totalFor(audience: AudienceFile, period: Period): number {
return audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
}
/** Each region with its figures for `period`, an arc to it from the studio, and the studio. */
function locationsFor(audience: AudienceFile, period: Period): Location<RegionFigures>[] {
const { studio, regions } = audience;
const total = totalFor(audience, period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(
({ id, title, lat, lng }): Location<RegionFigures> => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [
{ lat: studio.lat, lng: studio.lng },
{ lat, lng },
],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
}),
),
{ id: "studio", ...studio, listed: false },
];
}
/** A region on the map: its genre's letter, the genre, and its viewers; the studio keeps its own. */
function markerIcon({ data }: Location<RegionFigures>) {
if (data === undefined) return null;
return (
<span className="audience-card" data-genre={data.genre}>
<span className="audience-badge">{data.genre.charAt(0)}</span>
<span className="audience-card-text">
<span className="audience-genre">{data.genre}</span>
<span className="audience-viewers">{compact.format(data.viewers)}</span>
</span>
</span>
);
}
/** A region in the list: its name and viewers, its genre and share, and the share as a bar on a track. */
const regionEntry = ({ location }: ListEntry<RegionFigures>) => {
const { genre = "", viewers = 0, share = 0 } = location.data ?? {};
return (
<span className="audience-entry" data-genre={genre}>
<span className="audience-entry-title">{location.title}</span>
<span className="audience-entry-viewers">{compact.format(viewers)}</span>
<span className="audience-entry-genre">{genre}</span>
<span className="audience-entry-share">{share}%</span>
<span className="audience-track" aria-hidden="true">
<span className="audience-bar" style={{ width: `${share}%` }} />
</span>
</span>
);
};
function Audience() {
const [audience, setAudience] = useState<AudienceFile>();
const [period, setPeriod] = useState<Period>("1Y");
const [selectedId, setSelectedId] = useState<string>();
useEffect(() => {
fetch("/examples/data/audience.json")
.then((response) => response.json())
.then(setAudience);
}, []);
const locations = useMemo(
() => (audience ? locationsFor(audience, period) : []),
[audience, period],
);
return (
<MaplaceProvider
locations={locations}
view={FIRST_VIEW}
selectedId={selectedId}
// A click on an arc selects its region, as a click on the region's card does.
onSelectionChange={({ id }) => setSelectedId(id?.replace(/-arc$/, ""))}
>
<p>
<label htmlFor="audience-maplibre-react-period">Period</label>{" "}
<select
id="audience-maplibre-react-period"
value={period}
onChange={(event) => setPeriod(event.target.value as Period)}
>
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y">Last year</option>
</select>
</p>
<div className="map-and-list">
<MaplaceMap createAdapter={createMapLibreAdapter} className="map" markerIcon={markerIcon} />
<LocationList heading="By region">{regionEntry}</LocationList>
</div>
<p>
All viewers <output>{audience ? whole.format(totalFor(audience, period)) : ""}</output>
</p>
</MaplaceProvider>
);
}
createRoot(document.getElementById("audience-maplibre-react-root") as HTMLElement).render(
<StrictMode>
<Audience />
</StrictMode>,
);<!doctype html>
<!-- The page react.tsx renders into: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->Google's bootstrap loader, with your API key: from Google's docs
<script>
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "YOUR_KEY",
v: "weekly",
});
</script><!-- This example's look lives in the examples' styles/audience.css, which every version links. -->
<link rel="stylesheet" href="../styles/audience.css">
<style>
#audience-react-root .map-and-list { display: flex; height: 24rem; }
#audience-react-root .map { flex: 1 1 auto; min-width: 0; }
#audience-react-root .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#audience-react-root .map-and-list { flex-direction: column; height: 36rem; }
#audience-react-root .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="audience-react-root"></div>
<script type="module" src="./react.tsx"></script>import type { ListEntry, Location } from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
type Period = "1M" | "3M" | "1Y";
/** A region as the file has it: its top genre, and its viewers in each period. */
interface RegionRow {
readonly id: string;
readonly title: string;
readonly lat: number;
readonly lng: number;
readonly genre: string;
readonly viewers: Readonly<Record<Period, number>>;
}
/** The file: the studio the arcs leave from, and the regions. */
interface AudienceFile {
readonly studio: { readonly title: string; readonly lat: number; readonly lng: number };
readonly regions: readonly RegionRow[];
}
/** What a region's card and entry show for the period chosen. */
interface RegionFigures {
readonly genre: string;
readonly viewers: number;
readonly share: number;
}
/** Every region in view, with room at the edges for the cards. */
const FIRST_VIEW = { kind: "fit-all", padding: 64 } as const;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const whole = new Intl.NumberFormat("en");
/** Every region's viewers in `period`, added up. */
function totalFor(audience: AudienceFile, period: Period): number {
return audience.regions.reduce((sum, { viewers }) => sum + viewers[period], 0);
}
/** Each region with its figures for `period`, an arc to it from the studio, and the studio. */
function locationsFor(audience: AudienceFile, period: Period): Location<RegionFigures>[] {
const { studio, regions } = audience;
const total = totalFor(audience, period);
return [
...regions.map(({ id, title, lat, lng, genre, viewers }) => ({
id,
title,
lat,
lng,
data: { genre, viewers: viewers[period], share: Math.round((viewers[period] / total) * 100) },
})),
...regions.map(
({ id, title, lat, lng }): Location<RegionFigures> => ({
id: `${id}-arc`,
type: "polyline",
title: `${studio.title} → ${title}`,
path: [
{ lat: studio.lat, lng: studio.lng },
{ lat, lng },
],
curve: 0.2,
listed: false,
style: { stroke: "#6d28d9", strokeWidth: 2, strokeOpacity: 0.7 },
}),
),
{ id: "studio", ...studio, listed: false },
];
}
/** A region on the map: its genre's letter, the genre, and its viewers; the studio keeps its own. */
function markerIcon({ data }: Location<RegionFigures>) {
if (data === undefined) return null;
return (
<span className="audience-card" data-genre={data.genre}>
<span className="audience-badge">{data.genre.charAt(0)}</span>
<span className="audience-card-text">
<span className="audience-genre">{data.genre}</span>
<span className="audience-viewers">{compact.format(data.viewers)}</span>
</span>
</span>
);
}
/** A region in the list: its name and viewers, its genre and share, and the share as a bar on a track. */
const regionEntry = ({ location }: ListEntry<RegionFigures>) => {
const { genre = "", viewers = 0, share = 0 } = location.data ?? {};
return (
<span className="audience-entry" data-genre={genre}>
<span className="audience-entry-title">{location.title}</span>
<span className="audience-entry-viewers">{compact.format(viewers)}</span>
<span className="audience-entry-genre">{genre}</span>
<span className="audience-entry-share">{share}%</span>
<span className="audience-track" aria-hidden="true">
<span className="audience-bar" style={{ width: `${share}%` }} />
</span>
</span>
);
};
function Audience() {
const [audience, setAudience] = useState<AudienceFile>();
const [period, setPeriod] = useState<Period>("1Y");
const [selectedId, setSelectedId] = useState<string>();
useEffect(() => {
fetch("/examples/data/audience.json")
.then((response) => response.json())
.then(setAudience);
}, []);
const locations = useMemo(
() => (audience ? locationsFor(audience, period) : []),
[audience, period],
);
return (
<MaplaceProvider
locations={locations}
view={FIRST_VIEW}
selectedId={selectedId}
// A click on an arc selects its region, as a click on the region's card does.
onSelectionChange={({ id }) => setSelectedId(id?.replace(/-arc$/, ""))}
>
<p>
<label htmlFor="audience-react-period">Period</label>{" "}
<select
id="audience-react-period"
value={period}
onChange={(event) => setPeriod(event.target.value as Period)}
>
<option value="1M">Last month</option>
<option value="3M">Last 3 months</option>
<option value="1Y">Last year</option>
</select>
</p>
<div className="map-and-list">
<MaplaceMap createAdapter={createGoogleAdapter} className="map" markerIcon={markerIcon} />
<LocationList heading="By region">{regionEntry}</LocationList>
</div>
<p>
All viewers <output>{audience ? whole.format(totalFor(audience, period)) : ""}</output>
</p>
</MaplaceProvider>
);
}
createRoot(document.getElementById("audience-react-root") as HTMLElement).render(
<StrictMode>
<Audience />
</StrictMode>,
);How it works
A streaming service’s viewers by region: each region is a card on the map with its top genre’s letter, the genre and the viewers in the period chosen, an arc leaves the London studio for each one, and the list beside the map gives each region’s viewers and share, the share as a bar on a track. The select above the map swaps the period, and the total under it adds every region up. The figures are made up, for the example, in audience.json.
- HTML: the page’s script gives the file to the element’s
maplace, withsetLocations, and a list view of the page’s own (Maplace.defineListViewaroundMaplace.createListViewwithrender, defined as the page is read) draws each entry (List views). - Script and Bundler: each card is the region’s
icon, a function of itsdata(Icons), each arc a polyline with acurveandlisted: false(Polylines), andlist.renderbuilds each entry (List view options). The select callssetLocationswith the period’s figures; the ids stay, so the selection does too. - React:
markerIconon<MaplaceMap>draws the cards (nullleaves the studio its own dot), the entry is<LocationList>’s children, the period is state the locations are worked out from, and the selection is held in state (selectedIdandonSelectionChange) (<LocationList>). - Note: a click on an arc selects it, so a
selectionChangelistener selects its region instead, as a click on the card does.