Restyled venue map
A dark frame, pins coloured by category, a legend that filters them and a card of the venues, or of the one picked.
Map and code
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
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
Styled by whats-on.css
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- A look all your own, on OpenFreeMap's liberty style: a dark frame, pins of your markup
coloured by category, a count over the map's top left and a legend on its bottom left whose
chips show one category; Maplace.js's panel on the map made nothing. -->
<!-- This example's look lives in the examples' styles/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../../styles/whats-on.css">
<div id="whats-on-maplibre-frame" class="whats-on">
<div id="whats-on-maplibre-status" class="event-status over-map">
<output id="whats-on-maplibre-count" class="event-count"></output>
<span id="whats-on-maplibre-selected" class="event-selected" hidden></span>
</div>
<maplace-map id="whats-on-maplibre-map" class="whats-on-map" map-style="https://tiles.openfreemap.org/styles/liberty"
list="maplibre-whats-on-legend" list-position="bottom-left">
<maplace-location location-id="national-theatre" lat="51.507" lng="-0.1145" title="National Theatre" group="Theatre"
data-address="Upper Ground, London SE1 9PX" data-since="1976" data-known-for="Three stages on the South Bank">
<template data-icon><span class="pin" data-category="Theatre"></span></template>
</maplace-location>
<maplace-location location-id="globe" lat="51.5081" lng="-0.0972" title="Shakespeare's Globe" group="Theatre"
data-address="21 New Globe Walk, London SE1 9DT" data-since="1997" data-known-for="An open-air playhouse rebuilt after the 1599 original">
<template data-icon><span class="pin" data-category="Theatre"></span></template>
</maplace-location>
<maplace-location location-id="donmar" lat="51.5136" lng="-0.1254" title="Donmar Warehouse" group="Theatre"
data-address="41 Earlham Street, London WC2H 9LX" data-since="1977" data-known-for="A small studio theatre in Covent Garden">
<template data-icon><span class="pin" data-category="Theatre"></span></template>
</maplace-location>
<maplace-location location-id="royal-albert-hall" lat="51.501" lng="-0.1774" title="Royal Albert Hall" group="Concerts"
data-address="Kensington Gore, London SW7 2AP" data-since="1871" data-known-for="The BBC Proms, every summer">
<template data-icon><span class="pin" data-category="Concerts"></span></template>
</maplace-location>
<maplace-location location-id="wigmore-hall" lat="51.5165" lng="-0.149" title="Wigmore Hall" group="Concerts"
data-address="36 Wigmore Street, London W1U 2BP" data-since="1901" data-known-for="Chamber music and song recitals">
<template data-icon><span class="pin" data-category="Concerts"></span></template>
</maplace-location>
<maplace-location location-id="barbican" lat="51.5202" lng="-0.0938" title="Barbican Hall" group="Concerts"
data-address="Silk Street, London EC2Y 8DS" data-since="1982" data-known-for="Home of the London Symphony Orchestra">
<template data-icon><span class="pin" data-category="Concerts"></span></template>
</maplace-location>
<maplace-location location-id="borough-market" lat="51.5055" lng="-0.091" title="Borough Market" group="Markets"
data-address="8 Southwark Street, London SE1 1TL" data-since="1756" data-known-for="One of London's oldest food markets">
<template data-icon><span class="pin" data-category="Markets"></span></template>
</maplace-location>
<maplace-location location-id="camden-market" lat="51.5413" lng="-0.146" title="Camden Market" group="Markets"
data-address="Camden Lock Place, London NW1 8AF" data-since="1974" data-known-for="Stalls along the Regent's Canal">
<template data-icon><span class="pin" data-category="Markets"></span></template>
</maplace-location>
<maplace-location location-id="spitalfields" lat="51.5197" lng="-0.0754" title="Old Spitalfields Market" group="Markets"
data-address="16 Horner Square, London E1 6EW" data-since="1638" data-known-for="A Victorian market hall in the East End">
<template data-icon><span class="pin" data-category="Markets"></span></template>
</maplace-location>
<maplace-location location-id="british-library" lat="51.5299" lng="-0.1277" title="British Library" group="Talks"
data-address="96 Euston Road, London NW1 2DB" data-since="1973" data-known-for="The UK's national library, at St Pancras">
<template data-icon><span class="pin" data-category="Talks"></span></template>
</maplace-location>
<maplace-location location-id="conway-hall" lat="51.5203" lng="-0.1188" title="Conway Hall" group="Talks"
data-address="25 Red Lion Square, London WC1R 4RL" data-since="1929" data-known-for="Talks and debates, home of the Conway Hall Ethical Society">
<template data-icon><span class="pin" data-category="Talks"></span></template>
</maplace-location>
<maplace-location location-id="royal-institution" lat="51.5098" lng="-0.1425" title="Royal Institution" group="Talks"
data-address="21 Albemarle Street, London W1S 4BS" data-since="1799" data-known-for="The Christmas Lectures, given since 1825">
<template data-icon><span class="pin" data-category="Talks"></span></template>
</maplace-location>
</maplace-map>
<aside id="whats-on-maplibre-card" class="venue-card" aria-label="Venue">
<div class="venue-picker">
<p class="venue-list-category" hidden></p>
<p class="venue-empty">Pick a venue on the map, or here.</p>
<ul class="venue-list" aria-label="Venues"></ul>
</div>
<template>
<div class="venue">
<button type="button" class="venue-close" aria-label="Close"></button>
<p class="venue-category"></p>
<h3 class="venue-name">Venue</h3>
<dl>
<div><dt>Address</dt><dd class="venue-address"></dd></div>
<div><dt>Since</dt><dd class="venue-since"></dd></div>
<div><dt>Known for</dt><dd class="venue-known-for"></dd></div>
</dl>
</div>
</template>
</aside>
</div>
<script>
// The category the map shows alone, if any: the legend presses its chip, the card names it.
const whatsOnMaplibreShownAlone = (maplace) => {
const groups = maplace.getSnapshot().filter?.groups;
return groups?.length === 1 ? groups[0] : undefined;
};
// The legend, a list view of your own: a chip per category, in the venues' order, showing that
// category alone, or every one again once pressed. The chips are made once, so a chip pressed
// from the keyboard keeps its focus; a store change only moves the press.
Maplace.defineListView('maplibre-whats-on-legend', (maplace) => {
const legend = document.createElement('fieldset');
legend.className = 'event-legend';
legend.setAttribute('aria-label', 'Categories');
const categories = new Set(maplace.getSnapshot().locations.flatMap(({ group }) => group ?? []));
const chips = [...categories].map((category) => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'category-chip';
chip.dataset.category = category;
chip.setAttribute('aria-pressed', 'false');
chip.textContent = category;
chip.addEventListener('click', () => maplace.setFilter(whatsOnMaplibreShownAlone(maplace) === category ? undefined : [category]));
return chip;
});
legend.append(...chips);
let pressed;
const pressShownAlone = () => {
const alone = whatsOnMaplibreShownAlone(maplace);
if (alone === pressed) return;
pressed = alone;
for (const chip of chips) chip.setAttribute('aria-pressed', String(chip.dataset.category === alone));
};
pressShownAlone();
const unsubscribe = maplace.subscribe(pressShownAlone);
return { element: legend, destroy: () => { unsubscribe(); legend.remove(); } };
});
// Every venue fitted, with room at the edges for the count and the legend over the map, as the
// map opens; then the count over the map: how many venues are shown, of all of them, said again
// when that changes.
{
const maplace = document.getElementById('whats-on-maplibre-map').maplace;
maplace.fitAll({ padding: 80 });
const count = document.getElementById('whats-on-maplibre-count');
const writeCount = () => {
const snapshot = maplace.getSnapshot();
const shown = Maplace.listedLocations(snapshot).length;
const total = snapshot.locations.length;
const text = shown === total ? `${total} venues` : `${shown} of ${total} venues`;
if (count.textContent !== text) count.textContent = text;
};
writeCount();
maplace.subscribe(writeCount);
// Beside it, the name of the venue selected, marked with its category for its colour; hidden
// while none is. Not a live region: Maplace.js says each selection to a screen reader already.
const name = document.getElementById('whats-on-maplibre-selected');
const writeName = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
name.hidden = selected === undefined;
name.textContent = selected?.title ?? '';
name.dataset.category = selected?.group ?? '';
};
writeName(maplace.getSnapshot().selectedId);
maplace.on('selectionChange', ({ id }) => writeName(id));
// The card beside the map: the venue selected, its details from its location's data-
// attributes (its data), its category marked for its colour, made from the card's template and in the card
// only while a venue is selected, with a × closing it; or, while none is, the venues shown,
// each a button selecting it, under the category shown alone, if any, written again only when
// the venues shown change, as a hover changes the store too. Not a live region either.
const card = document.getElementById('whats-on-maplibre-card');
const picker = card.querySelector('.venue-picker');
const list = card.querySelector('.venue-list');
const categoryLine = card.querySelector('.venue-list-category');
const venuePart = card.querySelector('template').content.firstElementChild.cloneNode(true);
const close = venuePart.querySelector('.venue-close');
close.addEventListener('click', () => {
const closed = maplace.getSnapshot().selectedId ?? '';
maplace.select(undefined);
picker.querySelector(`.venue-pick[data-id="${CSS.escape(closed)}"]`)?.focus();
});
const venueEntry = ({ id, title, group }) => {
const pick = document.createElement('button');
pick.type = 'button';
pick.className = 'venue-pick';
pick.dataset.category = group ?? '';
pick.textContent = title ?? id;
pick.dataset.id = id;
pick.addEventListener('click', () => {
maplace.select(id);
close.focus();
});
const entry = document.createElement('li');
entry.append(pick);
return entry;
};
let listedIds;
const writeList = () => {
const listed = Maplace.listedLocations(maplace.getSnapshot());
const ids = listed.map(({ id }) => id).join();
if (ids === listedIds) return;
listedIds = ids;
const alone = whatsOnMaplibreShownAlone(maplace);
categoryLine.hidden = alone === undefined;
categoryLine.textContent = alone ?? '';
categoryLine.dataset.category = alone ?? '';
list.replaceChildren(...listed.map(venueEntry));
};
writeList();
maplace.subscribe(writeList);
const write = (selector, text) => { venuePart.querySelector(selector).textContent = text; };
const writeCard = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
picker.hidden = selected !== undefined;
if (selected === undefined) {
venuePart.remove();
return;
}
venuePart.dataset.category = selected.group;
write('.venue-category', selected.group);
write('.venue-name', selected.title);
write('.venue-address', selected.data.address);
write('.venue-since', selected.data.since);
write('.venue-known-for', selected.data.knownFor);
if (!venuePart.isConnected) card.append(venuePart);
};
writeCard(maplace.getSnapshot().selectedId);
maplace.on('selectionChange', ({ id }) => writeCard(id));
}
</script><!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- A look all your own, on Google's map without its map-type, Street View and camera controls:
a dark frame, pins of your markup coloured by category, a count over the map's top left and a
legend on its bottom left whose chips show one category; Maplace.js's panel on the map made
nothing. -->
<!-- This example's look lives in the examples' styles/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../styles/whats-on.css">
<div id="whats-on-frame" class="whats-on">
<div id="whats-on-status" class="event-status over-map">
<output id="whats-on-count" class="event-count"></output>
<span id="whats-on-selected" class="event-selected" hidden></span>
</div>
<maplace-map id="whats-on-map" class="whats-on-map" api-key="YOUR_KEY" map-options='{"mapTypeControl":false,"streetViewControl":false,"cameraControl":false}'
list="whats-on-legend" list-position="bottom-left">
<maplace-location location-id="national-theatre" lat="51.507" lng="-0.1145" title="National Theatre" group="Theatre"
data-address="Upper Ground, London SE1 9PX" data-since="1976" data-known-for="Three stages on the South Bank">
<template data-icon><span class="pin" data-category="Theatre"></span></template>
</maplace-location>
<maplace-location location-id="globe" lat="51.5081" lng="-0.0972" title="Shakespeare's Globe" group="Theatre"
data-address="21 New Globe Walk, London SE1 9DT" data-since="1997" data-known-for="An open-air playhouse rebuilt after the 1599 original">
<template data-icon><span class="pin" data-category="Theatre"></span></template>
</maplace-location>
<maplace-location location-id="donmar" lat="51.5136" lng="-0.1254" title="Donmar Warehouse" group="Theatre"
data-address="41 Earlham Street, London WC2H 9LX" data-since="1977" data-known-for="A small studio theatre in Covent Garden">
<template data-icon><span class="pin" data-category="Theatre"></span></template>
</maplace-location>
<maplace-location location-id="royal-albert-hall" lat="51.501" lng="-0.1774" title="Royal Albert Hall" group="Concerts"
data-address="Kensington Gore, London SW7 2AP" data-since="1871" data-known-for="The BBC Proms, every summer">
<template data-icon><span class="pin" data-category="Concerts"></span></template>
</maplace-location>
<maplace-location location-id="wigmore-hall" lat="51.5165" lng="-0.149" title="Wigmore Hall" group="Concerts"
data-address="36 Wigmore Street, London W1U 2BP" data-since="1901" data-known-for="Chamber music and song recitals">
<template data-icon><span class="pin" data-category="Concerts"></span></template>
</maplace-location>
<maplace-location location-id="barbican" lat="51.5202" lng="-0.0938" title="Barbican Hall" group="Concerts"
data-address="Silk Street, London EC2Y 8DS" data-since="1982" data-known-for="Home of the London Symphony Orchestra">
<template data-icon><span class="pin" data-category="Concerts"></span></template>
</maplace-location>
<maplace-location location-id="borough-market" lat="51.5055" lng="-0.091" title="Borough Market" group="Markets"
data-address="8 Southwark Street, London SE1 1TL" data-since="1756" data-known-for="One of London's oldest food markets">
<template data-icon><span class="pin" data-category="Markets"></span></template>
</maplace-location>
<maplace-location location-id="camden-market" lat="51.5413" lng="-0.146" title="Camden Market" group="Markets"
data-address="Camden Lock Place, London NW1 8AF" data-since="1974" data-known-for="Stalls along the Regent's Canal">
<template data-icon><span class="pin" data-category="Markets"></span></template>
</maplace-location>
<maplace-location location-id="spitalfields" lat="51.5197" lng="-0.0754" title="Old Spitalfields Market" group="Markets"
data-address="16 Horner Square, London E1 6EW" data-since="1638" data-known-for="A Victorian market hall in the East End">
<template data-icon><span class="pin" data-category="Markets"></span></template>
</maplace-location>
<maplace-location location-id="british-library" lat="51.5299" lng="-0.1277" title="British Library" group="Talks"
data-address="96 Euston Road, London NW1 2DB" data-since="1973" data-known-for="The UK's national library, at St Pancras">
<template data-icon><span class="pin" data-category="Talks"></span></template>
</maplace-location>
<maplace-location location-id="conway-hall" lat="51.5203" lng="-0.1188" title="Conway Hall" group="Talks"
data-address="25 Red Lion Square, London WC1R 4RL" data-since="1929" data-known-for="Talks and debates, home of the Conway Hall Ethical Society">
<template data-icon><span class="pin" data-category="Talks"></span></template>
</maplace-location>
<maplace-location location-id="royal-institution" lat="51.5098" lng="-0.1425" title="Royal Institution" group="Talks"
data-address="21 Albemarle Street, London W1S 4BS" data-since="1799" data-known-for="The Christmas Lectures, given since 1825">
<template data-icon><span class="pin" data-category="Talks"></span></template>
</maplace-location>
</maplace-map>
<aside id="whats-on-card" class="venue-card" aria-label="Venue">
<div class="venue-picker">
<p class="venue-list-category" hidden></p>
<p class="venue-empty">Pick a venue on the map, or here.</p>
<ul class="venue-list" aria-label="Venues"></ul>
</div>
<template>
<div class="venue">
<button type="button" class="venue-close" aria-label="Close"></button>
<p class="venue-category"></p>
<h3 class="venue-name">Venue</h3>
<dl>
<div><dt>Address</dt><dd class="venue-address"></dd></div>
<div><dt>Since</dt><dd class="venue-since"></dd></div>
<div><dt>Known for</dt><dd class="venue-known-for"></dd></div>
</dl>
</div>
</template>
</aside>
</div>
<script>
// The category the map shows alone, if any: the legend presses its chip, the card names it.
const whatsOnShownAlone = (maplace) => {
const groups = maplace.getSnapshot().filter?.groups;
return groups?.length === 1 ? groups[0] : undefined;
};
// The legend, a list view of your own: a chip per category, in the venues' order, showing that
// category alone, or every one again once pressed. The chips are made once, so a chip pressed
// from the keyboard keeps its focus; a store change only moves the press.
Maplace.defineListView('whats-on-legend', (maplace) => {
const legend = document.createElement('fieldset');
legend.className = 'event-legend';
legend.setAttribute('aria-label', 'Categories');
const categories = new Set(maplace.getSnapshot().locations.flatMap(({ group }) => group ?? []));
const chips = [...categories].map((category) => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'category-chip';
chip.dataset.category = category;
chip.setAttribute('aria-pressed', 'false');
chip.textContent = category;
chip.addEventListener('click', () => maplace.setFilter(whatsOnShownAlone(maplace) === category ? undefined : [category]));
return chip;
});
legend.append(...chips);
let pressed;
const pressShownAlone = () => {
const alone = whatsOnShownAlone(maplace);
if (alone === pressed) return;
pressed = alone;
for (const chip of chips) chip.setAttribute('aria-pressed', String(chip.dataset.category === alone));
};
pressShownAlone();
const unsubscribe = maplace.subscribe(pressShownAlone);
return { element: legend, destroy: () => { unsubscribe(); legend.remove(); } };
});
// Every venue fitted, with room at the edges for the count and the legend over the map, as the
// map opens; then the count over the map: how many venues are shown, of all of them, said again
// when that changes.
{
const maplace = document.getElementById('whats-on-map').maplace;
maplace.fitAll({ padding: 80 });
const count = document.getElementById('whats-on-count');
const writeCount = () => {
const snapshot = maplace.getSnapshot();
const shown = Maplace.listedLocations(snapshot).length;
const total = snapshot.locations.length;
const text = shown === total ? `${total} venues` : `${shown} of ${total} venues`;
if (count.textContent !== text) count.textContent = text;
};
writeCount();
maplace.subscribe(writeCount);
// Beside it, the name of the venue selected, marked with its category for its colour; hidden
// while none is. Not a live region: Maplace.js says each selection to a screen reader already.
const name = document.getElementById('whats-on-selected');
const writeName = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
name.hidden = selected === undefined;
name.textContent = selected?.title ?? '';
name.dataset.category = selected?.group ?? '';
};
writeName(maplace.getSnapshot().selectedId);
maplace.on('selectionChange', ({ id }) => writeName(id));
// The card beside the map: the venue selected, its details from its location's data-
// attributes (its data), its category marked for its colour, made from the card's template and in the card
// only while a venue is selected, with a × closing it; or, while none is, the venues shown,
// each a button selecting it, under the category shown alone, if any, written again only when
// the venues shown change, as a hover changes the store too. Not a live region either.
const card = document.getElementById('whats-on-card');
const picker = card.querySelector('.venue-picker');
const list = card.querySelector('.venue-list');
const categoryLine = card.querySelector('.venue-list-category');
const venuePart = card.querySelector('template').content.firstElementChild.cloneNode(true);
const close = venuePart.querySelector('.venue-close');
close.addEventListener('click', () => {
const closed = maplace.getSnapshot().selectedId ?? '';
maplace.select(undefined);
picker.querySelector(`.venue-pick[data-id="${CSS.escape(closed)}"]`)?.focus();
});
const venueEntry = ({ id, title, group }) => {
const pick = document.createElement('button');
pick.type = 'button';
pick.className = 'venue-pick';
pick.dataset.category = group ?? '';
pick.textContent = title ?? id;
pick.dataset.id = id;
pick.addEventListener('click', () => {
maplace.select(id);
close.focus();
});
const entry = document.createElement('li');
entry.append(pick);
return entry;
};
let listedIds;
const writeList = () => {
const listed = Maplace.listedLocations(maplace.getSnapshot());
const ids = listed.map(({ id }) => id).join();
if (ids === listedIds) return;
listedIds = ids;
const alone = whatsOnShownAlone(maplace);
categoryLine.hidden = alone === undefined;
categoryLine.textContent = alone ?? '';
categoryLine.dataset.category = alone ?? '';
list.replaceChildren(...listed.map(venueEntry));
};
writeList();
maplace.subscribe(writeList);
const write = (selector, text) => { venuePart.querySelector(selector).textContent = text; };
const writeCard = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
picker.hidden = selected !== undefined;
if (selected === undefined) {
venuePart.remove();
return;
}
venuePart.dataset.category = selected.group;
write('.venue-category', selected.group);
write('.venue-name', selected.title);
write('.venue-address', selected.data.address);
write('.venue-since', selected.data.since);
write('.venue-known-for', selected.data.knownFor);
if (!venuePart.isConnected) card.append(venuePart);
};
writeCard(maplace.getSnapshot().selectedId);
maplace.on('selectionChange', ({ id }) => writeCard(id));
}
</script><!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, what the map mounts on, and the map made with Maplace's store and adapter, on OpenFreeMap's liberty style; a count and a legend of your own on it, in Maplace.js's panel made nothing. -->
<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/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../../styles/whats-on.css">
<div id="whats-on-maplibre-script-frame" class="whats-on">
<div id="whats-on-maplibre-script-map" class="whats-on-map"></div>
<aside id="whats-on-maplibre-script-card" class="venue-card" aria-label="Venue">
<div class="venue-picker">
<p class="venue-list-category" hidden></p>
<p class="venue-empty">Pick a venue on the map, or here.</p>
<ul class="venue-list" aria-label="Venues"></ul>
</div>
<template>
<div class="venue">
<button type="button" class="venue-close" aria-label="Close"></button>
<p class="venue-category"></p>
<h3 class="venue-name">Venue</h3>
<dl>
<div><dt>Address</dt><dd class="venue-address"></dd></div>
<div><dt>Since</dt><dd class="venue-since"></dd></div>
<div><dt>Known for</dt><dd class="venue-known-for"></dd></div>
</dl>
</div>
</template>
</aside>
</div>
<script type="module">
const locations = [
venue("national-theatre", 51.507, -0.1145, "National Theatre", "Theatre", {
address: "Upper Ground, London SE1 9PX",
since: 1976,
knownFor: "Three stages on the South Bank",
}),
venue("globe", 51.5081, -0.0972, "Shakespeare's Globe", "Theatre", {
address: "21 New Globe Walk, London SE1 9DT",
since: 1997,
knownFor: "An open-air playhouse rebuilt after the 1599 original",
}),
venue("donmar", 51.5136, -0.1254, "Donmar Warehouse", "Theatre", {
address: "41 Earlham Street, London WC2H 9LX",
since: 1977,
knownFor: "A small studio theatre in Covent Garden",
}),
venue("royal-albert-hall", 51.501, -0.1774, "Royal Albert Hall", "Concerts", {
address: "Kensington Gore, London SW7 2AP",
since: 1871,
knownFor: "The BBC Proms, every summer",
}),
venue("wigmore-hall", 51.5165, -0.149, "Wigmore Hall", "Concerts", {
address: "36 Wigmore Street, London W1U 2BP",
since: 1901,
knownFor: "Chamber music and song recitals",
}),
venue("barbican", 51.5202, -0.0938, "Barbican Hall", "Concerts", {
address: "Silk Street, London EC2Y 8DS",
since: 1982,
knownFor: "Home of the London Symphony Orchestra",
}),
venue("borough-market", 51.5055, -0.091, "Borough Market", "Markets", {
address: "8 Southwark Street, London SE1 1TL",
since: 1756,
knownFor: "One of London's oldest food markets",
}),
venue("camden-market", 51.5413, -0.146, "Camden Market", "Markets", {
address: "Camden Lock Place, London NW1 8AF",
since: 1974,
knownFor: "Stalls along the Regent's Canal",
}),
venue("spitalfields", 51.5197, -0.0754, "Old Spitalfields Market", "Markets", {
address: "16 Horner Square, London E1 6EW",
since: 1638,
knownFor: "A Victorian market hall in the East End",
}),
venue("british-library", 51.5299, -0.1277, "British Library", "Talks", {
address: "96 Euston Road, London NW1 2DB",
since: 1973,
knownFor: "The UK's national library, at St Pancras",
}),
venue("conway-hall", 51.5203, -0.1188, "Conway Hall", "Talks", {
address: "25 Red Lion Square, London WC1R 4RL",
since: 1929,
knownFor: "Talks and debates, home of the Conway Hall Ethical Society",
}),
venue("royal-institution", 51.5098, -0.1425, "Royal Institution", "Talks", {
address: "21 Albemarle Street, London W1S 4BS",
since: 1799,
knownFor: "The Christmas Lectures, given since 1825",
}),
];
/** Every venue fitted, with room at the edges for the count and the legend over the map. */
const maplace = Maplace.createMaplace({ locations, view: { kind: "fit-all", padding: 80 } });
const adapter = Maplace.createMapLibreAdapter({ mapStyle: "https://tiles.openfreemap.org/styles/liberty" });
maplace.attach(adapter, "#whats-on-maplibre-script-map");
adapter.mountControl(eventLegend(maplace), "bottom-left");
adapter.mountControl(eventStatus(maplace), "top-left");
showVenueIn(document.querySelector("#whats-on-maplibre-script-card"), maplace);
/** A venue in its category, its pin coloured by it, with what the card says of it. */
function venue(id, lat, lng, title, group, data) {
return { id, lat, lng, title, group, data, icon: pinFor(group) };
}
/** A pin of your own, its colour the category's (`--category`, by `data-category` in the CSS). */
function pinFor(category) {
const pin = document.createElement("span");
pin.className = "pin";
pin.dataset.category = category;
return pin;
}
/** The count, and beside it the name of the venue selected, if any. */
function eventStatus(maplace) {
const status = document.createElement("div");
status.className = "event-status";
status.append(eventCount(maplace), selectedName(maplace));
return status;
}
/** How many venues are shown, of all of them, said again when that changes. */
function eventCount(maplace) {
const count = document.createElement("output");
count.className = "event-count";
const writeCount = () => {
const snapshot = maplace.getSnapshot();
const shown = Maplace.listedLocations(snapshot).length;
const total = snapshot.locations.length;
const text = shown === total ? `${total} venues` : `${shown} of ${total} venues`;
if (count.textContent !== text) count.textContent = text;
};
writeCount();
maplace.subscribe(writeCount);
return count;
}
/**
* The name of the venue selected, marked with its category for its colour; hidden while none is.
* Not a live region: Maplace.js says each selection to a screen reader already.
*/
function selectedName(maplace) {
const name = document.createElement("span");
name.className = "event-selected";
const writeName = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
name.hidden = selected === undefined;
name.textContent = selected?.title ?? "";
name.dataset.category = selected?.group ?? "";
};
writeName(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeName(id));
return name;
}
/**
* The card beside the map: the venue selected, its category marked for its colour, made from the
* card's template and in the card only while a venue is selected, with a × closing it;
* or, while none is, the venues shown, each a button selecting it. Not a live region: Maplace.js
* says each selection to a screen reader already.
*/
function showVenueIn(card, maplace) {
const picker = card.querySelector(".venue-picker");
const venuePart = card.querySelector("template").content.firstElementChild.cloneNode(true);
const close = venuePart.querySelector(".venue-close");
close.addEventListener("click", () => {
const closed = maplace.getSnapshot().selectedId ?? "";
maplace.select(undefined);
picker.querySelector(`.venue-pick[data-id="${CSS.escape(closed)}"]`)?.focus();
});
listVenuesIn(picker, maplace, () => close.focus());
const write = (selector, text) => {
venuePart.querySelector(selector).textContent = text;
};
const writeCard = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
const data = selected?.data;
picker.hidden = data !== undefined;
if (selected === undefined || data === undefined) {
venuePart.remove();
return;
}
venuePart.dataset.category = selected.group;
write(".venue-category", selected.group ?? "");
write(".venue-name", selected.title ?? "");
write(".venue-address", data.address);
write(".venue-since", String(data.since));
write(".venue-known-for", data.knownFor);
if (!venuePart.isConnected) card.append(venuePart);
};
writeCard(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeCard(id));
}
/**
* In the card's `picker`, a button per venue shown, selecting it and then calling `afterPick`, and
* above them the category shown alone, if any, marked for its colour; written again only when the
* venues shown change, as a hover changes the store too.
*/
function listVenuesIn(picker, maplace, afterPick) {
const categoryLine = picker.querySelector(".venue-list-category");
const list = picker.querySelector(".venue-list");
let listedIds;
const writeList = () => {
const listed = Maplace.listedLocations(maplace.getSnapshot());
const ids = listed.map(({ id }) => id).join();
if (ids === listedIds) return;
listedIds = ids;
const alone = shownAlone(maplace);
categoryLine.hidden = alone === undefined;
categoryLine.textContent = alone ?? "";
categoryLine.dataset.category = alone ?? "";
list.replaceChildren(...listed.map((location) => venueEntry(location, maplace, afterPick)));
};
writeList();
maplace.subscribe(writeList);
}
/** A venue in the card's list: a button selecting it, marked with its category for its colour. */
function venueEntry({ id, title, group }, maplace, afterPick) {
const pick = document.createElement("button");
pick.type = "button";
pick.className = "venue-pick";
pick.dataset.category = group ?? "";
pick.textContent = title ?? id;
pick.dataset.id = id;
pick.addEventListener("click", () => {
maplace.select(id);
afterPick();
});
const entry = document.createElement("li");
entry.append(pick);
return entry;
}
/**
* A chip per category, in the venues' order; the one shown alone is pressed. The chips are made once,
* so a chip pressed from the keyboard keeps its focus; a store change only moves the press.
*/
function eventLegend(maplace) {
const legend = document.createElement("fieldset");
legend.className = "event-legend";
legend.setAttribute("aria-label", "Categories");
const categories = new Set(maplace.getSnapshot().locations.flatMap(({ group }) => group ?? []));
const chips = [...categories].map((category) => categoryChip(maplace, category));
legend.append(...chips);
let pressed;
const pressShownAlone = () => {
const alone = shownAlone(maplace);
if (alone === pressed) return;
pressed = alone;
for (const chip of chips) {
chip.setAttribute("aria-pressed", String(chip.dataset.category === alone));
}
};
pressShownAlone();
maplace.subscribe(pressShownAlone);
return legend;
}
/** A toggle showing `category` alone, or every category again once pressed. */
function categoryChip(maplace, category) {
const chip = document.createElement("button");
chip.type = "button";
chip.className = "category-chip";
chip.dataset.category = category;
chip.setAttribute("aria-pressed", "false");
chip.textContent = category;
chip.addEventListener("click", () => {
maplace.setFilter(shownAlone(maplace) === category ? undefined : [category]);
});
return chip;
}
/** The category the map shows alone, if any. */
function shownAlone(maplace) {
const groups = maplace.getSnapshot().filter?.groups;
return groups?.length === 1 ? groups[0] : undefined;
}
</script><!doctype html>
<!-- A page of your own script: the CDN script, what the map mounts on, and the map made with Maplace's store and adapter, which adds Maps JS with your key, without its map-type, Street View and camera controls; a count and a legend of your own on it, in Maplace.js's panel made nothing. -->
<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/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../styles/whats-on.css">
<div id="whats-on-script-frame" class="whats-on">
<div id="whats-on-script-map" class="whats-on-map"></div>
<aside id="whats-on-script-card" class="venue-card" aria-label="Venue">
<div class="venue-picker">
<p class="venue-list-category" hidden></p>
<p class="venue-empty">Pick a venue on the map, or here.</p>
<ul class="venue-list" aria-label="Venues"></ul>
</div>
<template>
<div class="venue">
<button type="button" class="venue-close" aria-label="Close"></button>
<p class="venue-category"></p>
<h3 class="venue-name">Venue</h3>
<dl>
<div><dt>Address</dt><dd class="venue-address"></dd></div>
<div><dt>Since</dt><dd class="venue-since"></dd></div>
<div><dt>Known for</dt><dd class="venue-known-for"></dd></div>
</dl>
</div>
</template>
</aside>
</div>
<script type="module">
const locations = [
venue("national-theatre", 51.507, -0.1145, "National Theatre", "Theatre", {
address: "Upper Ground, London SE1 9PX",
since: 1976,
knownFor: "Three stages on the South Bank",
}),
venue("globe", 51.5081, -0.0972, "Shakespeare's Globe", "Theatre", {
address: "21 New Globe Walk, London SE1 9DT",
since: 1997,
knownFor: "An open-air playhouse rebuilt after the 1599 original",
}),
venue("donmar", 51.5136, -0.1254, "Donmar Warehouse", "Theatre", {
address: "41 Earlham Street, London WC2H 9LX",
since: 1977,
knownFor: "A small studio theatre in Covent Garden",
}),
venue("royal-albert-hall", 51.501, -0.1774, "Royal Albert Hall", "Concerts", {
address: "Kensington Gore, London SW7 2AP",
since: 1871,
knownFor: "The BBC Proms, every summer",
}),
venue("wigmore-hall", 51.5165, -0.149, "Wigmore Hall", "Concerts", {
address: "36 Wigmore Street, London W1U 2BP",
since: 1901,
knownFor: "Chamber music and song recitals",
}),
venue("barbican", 51.5202, -0.0938, "Barbican Hall", "Concerts", {
address: "Silk Street, London EC2Y 8DS",
since: 1982,
knownFor: "Home of the London Symphony Orchestra",
}),
venue("borough-market", 51.5055, -0.091, "Borough Market", "Markets", {
address: "8 Southwark Street, London SE1 1TL",
since: 1756,
knownFor: "One of London's oldest food markets",
}),
venue("camden-market", 51.5413, -0.146, "Camden Market", "Markets", {
address: "Camden Lock Place, London NW1 8AF",
since: 1974,
knownFor: "Stalls along the Regent's Canal",
}),
venue("spitalfields", 51.5197, -0.0754, "Old Spitalfields Market", "Markets", {
address: "16 Horner Square, London E1 6EW",
since: 1638,
knownFor: "A Victorian market hall in the East End",
}),
venue("british-library", 51.5299, -0.1277, "British Library", "Talks", {
address: "96 Euston Road, London NW1 2DB",
since: 1973,
knownFor: "The UK's national library, at St Pancras",
}),
venue("conway-hall", 51.5203, -0.1188, "Conway Hall", "Talks", {
address: "25 Red Lion Square, London WC1R 4RL",
since: 1929,
knownFor: "Talks and debates, home of the Conway Hall Ethical Society",
}),
venue("royal-institution", 51.5098, -0.1425, "Royal Institution", "Talks", {
address: "21 Albemarle Street, London W1S 4BS",
since: 1799,
knownFor: "The Christmas Lectures, given since 1825",
}),
];
/** Every venue fitted, with room at the edges for the count and the legend over the map. */
const maplace = Maplace.createMaplace({ locations, view: { kind: "fit-all", padding: 80 } });
const adapter = Maplace.createGoogleAdapter({ apiKey: "YOUR_KEY", mapOptions: { mapTypeControl: false, streetViewControl: false, cameraControl: false } });
maplace.attach(adapter, "#whats-on-script-map");
adapter.mountControl(eventLegend(maplace), "bottom-left");
adapter.mountControl(eventStatus(maplace), "top-left");
showVenueIn(document.querySelector("#whats-on-script-card"), maplace);
/** A venue in its category, its pin coloured by it, with what the card says of it. */
function venue(id, lat, lng, title, group, data) {
return { id, lat, lng, title, group, data, icon: pinFor(group) };
}
/** A pin of your own, its colour the category's (`--category`, by `data-category` in the CSS). */
function pinFor(category) {
const pin = document.createElement("span");
pin.className = "pin";
pin.dataset.category = category;
return pin;
}
/** The count, and beside it the name of the venue selected, if any. */
function eventStatus(maplace) {
const status = document.createElement("div");
status.className = "event-status";
status.append(eventCount(maplace), selectedName(maplace));
return status;
}
/** How many venues are shown, of all of them, said again when that changes. */
function eventCount(maplace) {
const count = document.createElement("output");
count.className = "event-count";
const writeCount = () => {
const snapshot = maplace.getSnapshot();
const shown = Maplace.listedLocations(snapshot).length;
const total = snapshot.locations.length;
const text = shown === total ? `${total} venues` : `${shown} of ${total} venues`;
if (count.textContent !== text) count.textContent = text;
};
writeCount();
maplace.subscribe(writeCount);
return count;
}
/**
* The name of the venue selected, marked with its category for its colour; hidden while none is.
* Not a live region: Maplace.js says each selection to a screen reader already.
*/
function selectedName(maplace) {
const name = document.createElement("span");
name.className = "event-selected";
const writeName = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
name.hidden = selected === undefined;
name.textContent = selected?.title ?? "";
name.dataset.category = selected?.group ?? "";
};
writeName(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeName(id));
return name;
}
/**
* The card beside the map: the venue selected, its category marked for its colour, made from the
* card's template and in the card only while a venue is selected, with a × closing it;
* or, while none is, the venues shown, each a button selecting it. Not a live region: Maplace.js
* says each selection to a screen reader already.
*/
function showVenueIn(card, maplace) {
const picker = card.querySelector(".venue-picker");
const venuePart = card.querySelector("template").content.firstElementChild.cloneNode(true);
const close = venuePart.querySelector(".venue-close");
close.addEventListener("click", () => {
const closed = maplace.getSnapshot().selectedId ?? "";
maplace.select(undefined);
picker.querySelector(`.venue-pick[data-id="${CSS.escape(closed)}"]`)?.focus();
});
listVenuesIn(picker, maplace, () => close.focus());
const write = (selector, text) => {
venuePart.querySelector(selector).textContent = text;
};
const writeCard = (id) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
const data = selected?.data;
picker.hidden = data !== undefined;
if (selected === undefined || data === undefined) {
venuePart.remove();
return;
}
venuePart.dataset.category = selected.group;
write(".venue-category", selected.group ?? "");
write(".venue-name", selected.title ?? "");
write(".venue-address", data.address);
write(".venue-since", String(data.since));
write(".venue-known-for", data.knownFor);
if (!venuePart.isConnected) card.append(venuePart);
};
writeCard(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeCard(id));
}
/**
* In the card's `picker`, a button per venue shown, selecting it and then calling `afterPick`, and
* above them the category shown alone, if any, marked for its colour; written again only when the
* venues shown change, as a hover changes the store too.
*/
function listVenuesIn(picker, maplace, afterPick) {
const categoryLine = picker.querySelector(".venue-list-category");
const list = picker.querySelector(".venue-list");
let listedIds;
const writeList = () => {
const listed = Maplace.listedLocations(maplace.getSnapshot());
const ids = listed.map(({ id }) => id).join();
if (ids === listedIds) return;
listedIds = ids;
const alone = shownAlone(maplace);
categoryLine.hidden = alone === undefined;
categoryLine.textContent = alone ?? "";
categoryLine.dataset.category = alone ?? "";
list.replaceChildren(...listed.map((location) => venueEntry(location, maplace, afterPick)));
};
writeList();
maplace.subscribe(writeList);
}
/** A venue in the card's list: a button selecting it, marked with its category for its colour. */
function venueEntry({ id, title, group }, maplace, afterPick) {
const pick = document.createElement("button");
pick.type = "button";
pick.className = "venue-pick";
pick.dataset.category = group ?? "";
pick.textContent = title ?? id;
pick.dataset.id = id;
pick.addEventListener("click", () => {
maplace.select(id);
afterPick();
});
const entry = document.createElement("li");
entry.append(pick);
return entry;
}
/**
* A chip per category, in the venues' order; the one shown alone is pressed. The chips are made once,
* so a chip pressed from the keyboard keeps its focus; a store change only moves the press.
*/
function eventLegend(maplace) {
const legend = document.createElement("fieldset");
legend.className = "event-legend";
legend.setAttribute("aria-label", "Categories");
const categories = new Set(maplace.getSnapshot().locations.flatMap(({ group }) => group ?? []));
const chips = [...categories].map((category) => categoryChip(maplace, category));
legend.append(...chips);
let pressed;
const pressShownAlone = () => {
const alone = shownAlone(maplace);
if (alone === pressed) return;
pressed = alone;
for (const chip of chips) {
chip.setAttribute("aria-pressed", String(chip.dataset.category === alone));
}
};
pressShownAlone();
maplace.subscribe(pressShownAlone);
return legend;
}
/** A toggle showing `category` alone, or every category again once pressed. */
function categoryChip(maplace, category) {
const chip = document.createElement("button");
chip.type = "button";
chip.className = "category-chip";
chip.dataset.category = category;
chip.setAttribute("aria-pressed", "false");
chip.textContent = category;
chip.addEventListener("click", () => {
maplace.setFilter(shownAlone(maplace) === category ? undefined : [category]);
});
return chip;
}
/** The category the map shows alone, if any. */
function shownAlone(maplace) {
const groups = maplace.getSnapshot().filter?.groups;
return groups?.length === 1 ? groups[0] : undefined;
}
</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/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../../styles/whats-on.css">
<div id="whats-on-maplibre-vanilla-frame" class="whats-on">
<div id="whats-on-maplibre-vanilla-map" class="whats-on-map"></div>
<aside id="whats-on-maplibre-vanilla-card" class="venue-card" aria-label="Venue">
<div class="venue-picker">
<p class="venue-list-category" hidden></p>
<p class="venue-empty">Pick a venue on the map, or here.</p>
<ul class="venue-list" aria-label="Venues"></ul>
</div>
<template>
<div class="venue">
<button type="button" class="venue-close" aria-label="Close"></button>
<p class="venue-category"></p>
<h3 class="venue-name">Venue</h3>
<dl>
<div><dt>Address</dt><dd class="venue-address"></dd></div>
<div><dt>Since</dt><dd class="venue-since"></dd></div>
<div><dt>Known for</dt><dd class="venue-known-for"></dd></div>
</dl>
</div>
</template>
</aside>
</div>
<script type="module" src="./vanilla.ts"></script>import "maplibre-gl/dist/maplibre-gl.css";
import {
createMaplace,
type Location,
type LocationGroup,
listedLocations,
type Maplace,
} from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
/** What the card beside the map says of a venue, besides its name and category. */
interface VenueDetails {
address: string;
since: number;
knownFor: string;
}
const locations: Location<VenueDetails>[] = [
venue("national-theatre", 51.507, -0.1145, "National Theatre", "Theatre", {
address: "Upper Ground, London SE1 9PX",
since: 1976,
knownFor: "Three stages on the South Bank",
}),
venue("globe", 51.5081, -0.0972, "Shakespeare's Globe", "Theatre", {
address: "21 New Globe Walk, London SE1 9DT",
since: 1997,
knownFor: "An open-air playhouse rebuilt after the 1599 original",
}),
venue("donmar", 51.5136, -0.1254, "Donmar Warehouse", "Theatre", {
address: "41 Earlham Street, London WC2H 9LX",
since: 1977,
knownFor: "A small studio theatre in Covent Garden",
}),
venue("royal-albert-hall", 51.501, -0.1774, "Royal Albert Hall", "Concerts", {
address: "Kensington Gore, London SW7 2AP",
since: 1871,
knownFor: "The BBC Proms, every summer",
}),
venue("wigmore-hall", 51.5165, -0.149, "Wigmore Hall", "Concerts", {
address: "36 Wigmore Street, London W1U 2BP",
since: 1901,
knownFor: "Chamber music and song recitals",
}),
venue("barbican", 51.5202, -0.0938, "Barbican Hall", "Concerts", {
address: "Silk Street, London EC2Y 8DS",
since: 1982,
knownFor: "Home of the London Symphony Orchestra",
}),
venue("borough-market", 51.5055, -0.091, "Borough Market", "Markets", {
address: "8 Southwark Street, London SE1 1TL",
since: 1756,
knownFor: "One of London's oldest food markets",
}),
venue("camden-market", 51.5413, -0.146, "Camden Market", "Markets", {
address: "Camden Lock Place, London NW1 8AF",
since: 1974,
knownFor: "Stalls along the Regent's Canal",
}),
venue("spitalfields", 51.5197, -0.0754, "Old Spitalfields Market", "Markets", {
address: "16 Horner Square, London E1 6EW",
since: 1638,
knownFor: "A Victorian market hall in the East End",
}),
venue("british-library", 51.5299, -0.1277, "British Library", "Talks", {
address: "96 Euston Road, London NW1 2DB",
since: 1973,
knownFor: "The UK's national library, at St Pancras",
}),
venue("conway-hall", 51.5203, -0.1188, "Conway Hall", "Talks", {
address: "25 Red Lion Square, London WC1R 4RL",
since: 1929,
knownFor: "Talks and debates, home of the Conway Hall Ethical Society",
}),
venue("royal-institution", 51.5098, -0.1425, "Royal Institution", "Talks", {
address: "21 Albemarle Street, London W1S 4BS",
since: 1799,
knownFor: "The Christmas Lectures, given since 1825",
}),
];
/** Every venue fitted, with room at the edges for the count and the legend over the map. */
const maplace = createMaplace({ locations, view: { kind: "fit-all", padding: 80 } });
const adapter = createMapLibreAdapter({
mapStyle: "https://tiles.openfreemap.org/styles/liberty",
});
maplace.attach(adapter, "#whats-on-maplibre-vanilla-map");
adapter.mountControl(eventLegend(maplace), "bottom-left");
adapter.mountControl(eventStatus(maplace), "top-left");
showVenueIn(document.querySelector("#whats-on-maplibre-vanilla-card") as HTMLElement, maplace);
/** A venue in its category, its pin coloured by it, with what the card says of it. */
function venue(
id: string,
lat: number,
lng: number,
title: string,
group: string,
data: VenueDetails,
): Location<VenueDetails> {
return { id, lat, lng, title, group, data, icon: pinFor(group) };
}
/** A pin of your own, its colour the category's (`--category`, by `data-category` in the CSS). */
function pinFor(category: string): HTMLElement {
const pin = document.createElement("span");
pin.className = "pin";
pin.dataset.category = category;
return pin;
}
/** The count, and beside it the name of the venue selected, if any. */
function eventStatus(maplace: Maplace): HTMLElement {
const status = document.createElement("div");
status.className = "event-status";
status.append(eventCount(maplace), selectedName(maplace));
return status;
}
/** How many venues are shown, of all of them, said again when that changes. */
function eventCount(maplace: Maplace): HTMLOutputElement {
const count = document.createElement("output");
count.className = "event-count";
const writeCount = () => {
const snapshot = maplace.getSnapshot();
const shown = listedLocations(snapshot).length;
const total = snapshot.locations.length;
const text = shown === total ? `${total} venues` : `${shown} of ${total} venues`;
if (count.textContent !== text) count.textContent = text;
};
writeCount();
maplace.subscribe(writeCount);
return count;
}
/**
* The name of the venue selected, marked with its category for its colour; hidden while none is.
* Not a live region: Maplace.js says each selection to a screen reader already.
*/
function selectedName(maplace: Maplace): HTMLElement {
const name = document.createElement("span");
name.className = "event-selected";
const writeName = (id: string | undefined) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
name.hidden = selected === undefined;
name.textContent = selected?.title ?? "";
name.dataset.category = categoryOf(selected?.group);
};
writeName(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeName(id));
return name;
}
/**
* The card beside the map: the venue selected, its category marked for its colour, made from the
* card's template and in the card only while a venue is selected, with a × closing it; or,
* while none is, the venues shown, each a button selecting it. Not a live region: Maplace.js says each
* selection to a screen reader already.
*/
function showVenueIn(card: HTMLElement, maplace: Maplace<VenueDetails>): void {
const picker = card.querySelector(".venue-picker") as HTMLElement;
const template = card.querySelector("template") as HTMLTemplateElement;
const venuePart = template.content.firstElementChild?.cloneNode(true) as HTMLElement;
const close = venuePart.querySelector(".venue-close") as HTMLButtonElement;
close.addEventListener("click", () => {
const closed = maplace.getSnapshot().selectedId ?? "";
maplace.select(undefined);
picker.querySelector<HTMLElement>(`.venue-pick[data-id="${CSS.escape(closed)}"]`)?.focus();
});
listVenuesIn(picker, maplace, () => close.focus());
const write = (selector: string, text: string) => {
(venuePart.querySelector(selector) as HTMLElement).textContent = text;
};
const writeCard = (id: string | undefined) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
const data = selected?.data;
picker.hidden = data !== undefined;
if (selected === undefined || data === undefined) {
venuePart.remove();
return;
}
venuePart.dataset.category = categoryOf(selected.group);
write(".venue-category", categoryOf(selected.group));
write(".venue-name", selected.title ?? "");
write(".venue-address", data.address);
write(".venue-since", String(data.since));
write(".venue-known-for", data.knownFor);
if (!venuePart.isConnected) card.append(venuePart);
};
writeCard(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeCard(id));
}
/**
* In the card's `picker`, a button per venue shown, selecting it and then calling `afterPick`, and
* above them the category shown alone, if any, marked for its colour; written again only when the
* venues shown change, as a hover changes the store too.
*/
function listVenuesIn(picker: HTMLElement, maplace: Maplace, afterPick: () => void): void {
const categoryLine = picker.querySelector(".venue-list-category") as HTMLElement;
const list = picker.querySelector(".venue-list") as HTMLElement;
let listedIds: string | undefined;
const writeList = () => {
const listed = listedLocations(maplace.getSnapshot());
const ids = listed.map(({ id }) => id).join();
if (ids === listedIds) return;
listedIds = ids;
const alone = shownAlone(maplace);
categoryLine.hidden = alone === undefined;
categoryLine.textContent = alone ?? "";
categoryLine.dataset.category = alone ?? "";
list.replaceChildren(...listed.map((location) => venueEntry(location, maplace, afterPick)));
};
writeList();
maplace.subscribe(writeList);
}
/** A venue in the card's list: a button selecting it, marked with its category for its colour. */
function venueEntry({ id, title, group }: Location, maplace: Maplace, afterPick: () => void) {
const pick = document.createElement("button");
pick.type = "button";
pick.className = "venue-pick";
pick.dataset.category = categoryOf(group);
pick.textContent = title ?? id;
pick.dataset.id = id;
pick.addEventListener("click", () => {
maplace.select(id);
afterPick();
});
const entry = document.createElement("li");
entry.append(pick);
return entry;
}
/**
* A chip per category, in the venues' order; the one shown alone is pressed. The chips are made
* once, so a chip pressed from the keyboard keeps its focus; a store change only moves the press.
*/
function eventLegend(maplace: Maplace): HTMLElement {
const legend = document.createElement("fieldset");
legend.className = "event-legend";
legend.setAttribute("aria-label", "Categories");
const categories = new Set(maplace.getSnapshot().locations.flatMap(({ group }) => group ?? []));
const chips = [...categories].map((category) => categoryChip(maplace, category));
legend.append(...chips);
let pressed: string | undefined;
const pressShownAlone = () => {
const alone = shownAlone(maplace);
if (alone === pressed) return;
pressed = alone;
for (const chip of chips) {
chip.setAttribute("aria-pressed", String(chip.dataset.category === alone));
}
};
pressShownAlone();
maplace.subscribe(pressShownAlone);
return legend;
}
/** A toggle showing `category` alone, or every category again once pressed. */
function categoryChip(maplace: Maplace, category: string): HTMLButtonElement {
const chip = document.createElement("button");
chip.type = "button";
chip.className = "category-chip";
chip.dataset.category = category;
chip.setAttribute("aria-pressed", "false");
chip.textContent = category;
chip.addEventListener("click", () => {
maplace.setFilter(shownAlone(maplace) === category ? undefined : [category]);
});
return chip;
}
/** The category the map shows alone, if any. */
function shownAlone(maplace: Maplace): string | undefined {
const groups = maplace.getSnapshot().filter?.groups;
return groups?.length === 1 ? categoryOf(groups[0]) || undefined : undefined;
}
/** A venue's category: its group, a plain name on this map. */
function categoryOf(group: LocationGroup | undefined): string {
return typeof group === "string" ? group : "";
}<!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/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../styles/whats-on.css">
<div id="whats-on-vanilla-frame" class="whats-on">
<div id="whats-on-vanilla-map" class="whats-on-map"></div>
<aside id="whats-on-vanilla-card" class="venue-card" aria-label="Venue">
<div class="venue-picker">
<p class="venue-list-category" hidden></p>
<p class="venue-empty">Pick a venue on the map, or here.</p>
<ul class="venue-list" aria-label="Venues"></ul>
</div>
<template>
<div class="venue">
<button type="button" class="venue-close" aria-label="Close"></button>
<p class="venue-category"></p>
<h3 class="venue-name">Venue</h3>
<dl>
<div><dt>Address</dt><dd class="venue-address"></dd></div>
<div><dt>Since</dt><dd class="venue-since"></dd></div>
<div><dt>Known for</dt><dd class="venue-known-for"></dd></div>
</dl>
</div>
</template>
</aside>
</div>
<script type="module" src="./vanilla.ts"></script>import {
createMaplace,
type Location,
type LocationGroup,
listedLocations,
type Maplace,
} from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
/** What the card beside the map says of a venue, besides its name and category. */
interface VenueDetails {
address: string;
since: number;
knownFor: string;
}
const locations: Location<VenueDetails>[] = [
venue("national-theatre", 51.507, -0.1145, "National Theatre", "Theatre", {
address: "Upper Ground, London SE1 9PX",
since: 1976,
knownFor: "Three stages on the South Bank",
}),
venue("globe", 51.5081, -0.0972, "Shakespeare's Globe", "Theatre", {
address: "21 New Globe Walk, London SE1 9DT",
since: 1997,
knownFor: "An open-air playhouse rebuilt after the 1599 original",
}),
venue("donmar", 51.5136, -0.1254, "Donmar Warehouse", "Theatre", {
address: "41 Earlham Street, London WC2H 9LX",
since: 1977,
knownFor: "A small studio theatre in Covent Garden",
}),
venue("royal-albert-hall", 51.501, -0.1774, "Royal Albert Hall", "Concerts", {
address: "Kensington Gore, London SW7 2AP",
since: 1871,
knownFor: "The BBC Proms, every summer",
}),
venue("wigmore-hall", 51.5165, -0.149, "Wigmore Hall", "Concerts", {
address: "36 Wigmore Street, London W1U 2BP",
since: 1901,
knownFor: "Chamber music and song recitals",
}),
venue("barbican", 51.5202, -0.0938, "Barbican Hall", "Concerts", {
address: "Silk Street, London EC2Y 8DS",
since: 1982,
knownFor: "Home of the London Symphony Orchestra",
}),
venue("borough-market", 51.5055, -0.091, "Borough Market", "Markets", {
address: "8 Southwark Street, London SE1 1TL",
since: 1756,
knownFor: "One of London's oldest food markets",
}),
venue("camden-market", 51.5413, -0.146, "Camden Market", "Markets", {
address: "Camden Lock Place, London NW1 8AF",
since: 1974,
knownFor: "Stalls along the Regent's Canal",
}),
venue("spitalfields", 51.5197, -0.0754, "Old Spitalfields Market", "Markets", {
address: "16 Horner Square, London E1 6EW",
since: 1638,
knownFor: "A Victorian market hall in the East End",
}),
venue("british-library", 51.5299, -0.1277, "British Library", "Talks", {
address: "96 Euston Road, London NW1 2DB",
since: 1973,
knownFor: "The UK's national library, at St Pancras",
}),
venue("conway-hall", 51.5203, -0.1188, "Conway Hall", "Talks", {
address: "25 Red Lion Square, London WC1R 4RL",
since: 1929,
knownFor: "Talks and debates, home of the Conway Hall Ethical Society",
}),
venue("royal-institution", 51.5098, -0.1425, "Royal Institution", "Talks", {
address: "21 Albemarle Street, London W1S 4BS",
since: 1799,
knownFor: "The Christmas Lectures, given since 1825",
}),
];
/** Every venue fitted, with room at the edges for the count and the legend over the map. */
const maplace = createMaplace({ locations, view: { kind: "fit-all", padding: 80 } });
const adapter = createGoogleAdapter({
mapOptions: { mapTypeControl: false, streetViewControl: false, cameraControl: false },
});
maplace.attach(adapter, "#whats-on-vanilla-map");
adapter.mountControl(eventLegend(maplace), "bottom-left");
adapter.mountControl(eventStatus(maplace), "top-left");
showVenueIn(document.querySelector("#whats-on-vanilla-card") as HTMLElement, maplace);
/** A venue in its category, its pin coloured by it, with what the card says of it. */
function venue(
id: string,
lat: number,
lng: number,
title: string,
group: string,
data: VenueDetails,
): Location<VenueDetails> {
return { id, lat, lng, title, group, data, icon: pinFor(group) };
}
/** A pin of your own, its colour the category's (`--category`, by `data-category` in the CSS). */
function pinFor(category: string): HTMLElement {
const pin = document.createElement("span");
pin.className = "pin";
pin.dataset.category = category;
return pin;
}
/** The count, and beside it the name of the venue selected, if any. */
function eventStatus(maplace: Maplace): HTMLElement {
const status = document.createElement("div");
status.className = "event-status";
status.append(eventCount(maplace), selectedName(maplace));
return status;
}
/** How many venues are shown, of all of them, said again when that changes. */
function eventCount(maplace: Maplace): HTMLOutputElement {
const count = document.createElement("output");
count.className = "event-count";
const writeCount = () => {
const snapshot = maplace.getSnapshot();
const shown = listedLocations(snapshot).length;
const total = snapshot.locations.length;
const text = shown === total ? `${total} venues` : `${shown} of ${total} venues`;
if (count.textContent !== text) count.textContent = text;
};
writeCount();
maplace.subscribe(writeCount);
return count;
}
/**
* The name of the venue selected, marked with its category for its colour; hidden while none is.
* Not a live region: Maplace.js says each selection to a screen reader already.
*/
function selectedName(maplace: Maplace): HTMLElement {
const name = document.createElement("span");
name.className = "event-selected";
const writeName = (id: string | undefined) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
name.hidden = selected === undefined;
name.textContent = selected?.title ?? "";
name.dataset.category = categoryOf(selected?.group);
};
writeName(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeName(id));
return name;
}
/**
* The card beside the map: the venue selected, its category marked for its colour, made from the
* card's template and in the card only while a venue is selected, with a × closing it; or,
* while none is, the venues shown, each a button selecting it. Not a live region: Maplace.js says each
* selection to a screen reader already.
*/
function showVenueIn(card: HTMLElement, maplace: Maplace<VenueDetails>): void {
const picker = card.querySelector(".venue-picker") as HTMLElement;
const template = card.querySelector("template") as HTMLTemplateElement;
const venuePart = template.content.firstElementChild?.cloneNode(true) as HTMLElement;
const close = venuePart.querySelector(".venue-close") as HTMLButtonElement;
close.addEventListener("click", () => {
const closed = maplace.getSnapshot().selectedId ?? "";
maplace.select(undefined);
picker.querySelector<HTMLElement>(`.venue-pick[data-id="${CSS.escape(closed)}"]`)?.focus();
});
listVenuesIn(picker, maplace, () => close.focus());
const write = (selector: string, text: string) => {
(venuePart.querySelector(selector) as HTMLElement).textContent = text;
};
const writeCard = (id: string | undefined) => {
const selected = maplace.getSnapshot().locations.find((location) => location.id === id);
const data = selected?.data;
picker.hidden = data !== undefined;
if (selected === undefined || data === undefined) {
venuePart.remove();
return;
}
venuePart.dataset.category = categoryOf(selected.group);
write(".venue-category", categoryOf(selected.group));
write(".venue-name", selected.title ?? "");
write(".venue-address", data.address);
write(".venue-since", String(data.since));
write(".venue-known-for", data.knownFor);
if (!venuePart.isConnected) card.append(venuePart);
};
writeCard(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", ({ id }) => writeCard(id));
}
/**
* In the card's `picker`, a button per venue shown, selecting it and then calling `afterPick`, and
* above them the category shown alone, if any, marked for its colour; written again only when the
* venues shown change, as a hover changes the store too.
*/
function listVenuesIn(picker: HTMLElement, maplace: Maplace, afterPick: () => void): void {
const categoryLine = picker.querySelector(".venue-list-category") as HTMLElement;
const list = picker.querySelector(".venue-list") as HTMLElement;
let listedIds: string | undefined;
const writeList = () => {
const listed = listedLocations(maplace.getSnapshot());
const ids = listed.map(({ id }) => id).join();
if (ids === listedIds) return;
listedIds = ids;
const alone = shownAlone(maplace);
categoryLine.hidden = alone === undefined;
categoryLine.textContent = alone ?? "";
categoryLine.dataset.category = alone ?? "";
list.replaceChildren(...listed.map((location) => venueEntry(location, maplace, afterPick)));
};
writeList();
maplace.subscribe(writeList);
}
/** A venue in the card's list: a button selecting it, marked with its category for its colour. */
function venueEntry({ id, title, group }: Location, maplace: Maplace, afterPick: () => void) {
const pick = document.createElement("button");
pick.type = "button";
pick.className = "venue-pick";
pick.dataset.category = categoryOf(group);
pick.textContent = title ?? id;
pick.dataset.id = id;
pick.addEventListener("click", () => {
maplace.select(id);
afterPick();
});
const entry = document.createElement("li");
entry.append(pick);
return entry;
}
/**
* A chip per category, in the venues' order; the one shown alone is pressed. The chips are made
* once, so a chip pressed from the keyboard keeps its focus; a store change only moves the press.
*/
function eventLegend(maplace: Maplace): HTMLElement {
const legend = document.createElement("fieldset");
legend.className = "event-legend";
legend.setAttribute("aria-label", "Categories");
const categories = new Set(maplace.getSnapshot().locations.flatMap(({ group }) => group ?? []));
const chips = [...categories].map((category) => categoryChip(maplace, category));
legend.append(...chips);
let pressed: string | undefined;
const pressShownAlone = () => {
const alone = shownAlone(maplace);
if (alone === pressed) return;
pressed = alone;
for (const chip of chips) {
chip.setAttribute("aria-pressed", String(chip.dataset.category === alone));
}
};
pressShownAlone();
maplace.subscribe(pressShownAlone);
return legend;
}
/** A toggle showing `category` alone, or every category again once pressed. */
function categoryChip(maplace: Maplace, category: string): HTMLButtonElement {
const chip = document.createElement("button");
chip.type = "button";
chip.className = "category-chip";
chip.dataset.category = category;
chip.setAttribute("aria-pressed", "false");
chip.textContent = category;
chip.addEventListener("click", () => {
maplace.setFilter(shownAlone(maplace) === category ? undefined : [category]);
});
return chip;
}
/** The category the map shows alone, if any. */
function shownAlone(maplace: Maplace): string | undefined {
const groups = maplace.getSnapshot().filter?.groups;
return groups?.length === 1 ? categoryOf(groups[0]) || undefined : undefined;
}
/** A venue's category: its group, a plain name on this map. */
function categoryOf(group: LocationGroup | undefined): string {
return typeof group === "string" ? group : "";
}<!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/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../../styles/whats-on.css">
<div id="whats-on-maplibre-react-root" class="whats-on"></div>
<script type="module" src="./react.tsx"></script>import "maplibre-gl/dist/maplibre-gl.css";
import { type Location, listedLocations, type Snapshot, type View } from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
import { MapControl, MaplaceMap, MaplaceProvider, useMaplace } from "@maplacejs/maplace/react";
import { StrictMode, useRef, useSyncExternalStore } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
/** What the card beside the map says of a venue, besides its name and category. */
interface VenueDetails {
address: string;
since: number;
knownFor: string;
}
const venues: Location<VenueDetails>[] = [
venue("national-theatre", 51.507, -0.1145, "National Theatre", "Theatre", {
address: "Upper Ground, London SE1 9PX",
since: 1976,
knownFor: "Three stages on the South Bank",
}),
venue("globe", 51.5081, -0.0972, "Shakespeare's Globe", "Theatre", {
address: "21 New Globe Walk, London SE1 9DT",
since: 1997,
knownFor: "An open-air playhouse rebuilt after the 1599 original",
}),
venue("donmar", 51.5136, -0.1254, "Donmar Warehouse", "Theatre", {
address: "41 Earlham Street, London WC2H 9LX",
since: 1977,
knownFor: "A small studio theatre in Covent Garden",
}),
venue("royal-albert-hall", 51.501, -0.1774, "Royal Albert Hall", "Concerts", {
address: "Kensington Gore, London SW7 2AP",
since: 1871,
knownFor: "The BBC Proms, every summer",
}),
venue("wigmore-hall", 51.5165, -0.149, "Wigmore Hall", "Concerts", {
address: "36 Wigmore Street, London W1U 2BP",
since: 1901,
knownFor: "Chamber music and song recitals",
}),
venue("barbican", 51.5202, -0.0938, "Barbican Hall", "Concerts", {
address: "Silk Street, London EC2Y 8DS",
since: 1982,
knownFor: "Home of the London Symphony Orchestra",
}),
venue("borough-market", 51.5055, -0.091, "Borough Market", "Markets", {
address: "8 Southwark Street, London SE1 1TL",
since: 1756,
knownFor: "One of London's oldest food markets",
}),
venue("camden-market", 51.5413, -0.146, "Camden Market", "Markets", {
address: "Camden Lock Place, London NW1 8AF",
since: 1974,
knownFor: "Stalls along the Regent's Canal",
}),
venue("spitalfields", 51.5197, -0.0754, "Old Spitalfields Market", "Markets", {
address: "16 Horner Square, London E1 6EW",
since: 1638,
knownFor: "A Victorian market hall in the East End",
}),
venue("british-library", 51.5299, -0.1277, "British Library", "Talks", {
address: "96 Euston Road, London NW1 2DB",
since: 1973,
knownFor: "The UK's national library, at St Pancras",
}),
venue("conway-hall", 51.5203, -0.1188, "Conway Hall", "Talks", {
address: "25 Red Lion Square, London WC1R 4RL",
since: 1929,
knownFor: "Talks and debates, home of the Conway Hall Ethical Society",
}),
venue("royal-institution", 51.5098, -0.1425, "Royal Institution", "Talks", {
address: "21 Albemarle Street, London W1S 4BS",
since: 1799,
knownFor: "The Christmas Lectures, given since 1825",
}),
];
/** A venue in its category, with what the card says of it. */
function venue(
id: string,
lat: number,
lng: number,
title: string,
group: string,
data: VenueDetails,
): Location<VenueDetails> {
return { id, lat, lng, title, group, data };
}
/** A map on OpenFreeMap's liberty style. */
const createAdapter = () =>
createMapLibreAdapter({ mapStyle: "https://tiles.openfreemap.org/styles/liberty" });
/** Every venue fitted, with room at the edges for the count and the legend over the map. */
const firstView: View = { kind: "fit-all", padding: 80 };
/**
* A pin of your own, its colour the category's (`--category`, by `data-category` in the CSS), in a
* node Maplace.js keeps for each marker and marks `data-hovered` and `data-selected`.
*/
const markerIcon = ({ group }: Location) => <span className="pin" data-category={group} />;
/** The count, and beside it the name of the venue selected, if any. */
function EventStatus() {
return (
<div className="event-status">
<EventCount />
<SelectedName />
</div>
);
}
/** How many venues are shown, of all of them; read as text, so a hover renders nothing. */
function EventCount() {
const maplace = useMaplace();
const text = useSyncExternalStore(maplace.subscribe, () => countText(maplace.getSnapshot()));
return <output className="event-count">{text}</output>;
}
function countText(snapshot: Snapshot): string {
const shown = listedLocations(snapshot).length;
const total = snapshot.locations.length;
return shown === total ? `${total} venues` : `${shown} of ${total} venues`;
}
/**
* The name of the venue selected, marked with its category for its colour; hidden while none is.
* Not a live region: Maplace.js says each selection to a screen reader already.
*/
function SelectedName() {
const maplace = useMaplace<VenueDetails>();
const selected = useSyncExternalStore(maplace.subscribe, () => selectedIn(maplace.getSnapshot()));
return (
<span
className="event-selected"
data-category={selected?.group}
hidden={selected === undefined}
>
{selected?.title}
</span>
);
}
function selectedIn({
locations,
selectedId,
}: Snapshot<VenueDetails>): Location<VenueDetails> | undefined {
return locations.find(({ id }) => id === selectedId);
}
/**
* The card beside the map: the venue selected, its category marked for its colour, with a × closing
* it; or, while none is, the venues shown, each a button selecting it, under the category shown
* alone, if any. A press moves the focus to what takes the button's place, the card rendered at
* once for it. Not a live region: Maplace.js says each selection to a screen reader already.
*/
function VenueCard() {
const maplace = useMaplace<VenueDetails>();
const selected = useSyncExternalStore(maplace.subscribe, () => selectedIn(maplace.getSnapshot()));
const listed = useListedVenues();
const shownAlone = useSyncExternalStore(maplace.subscribe, () =>
shownAloneIn(maplace.getSnapshot()),
);
const card = useRef<HTMLElement>(null);
const selectAndFocus = (id: string | undefined, toFocus: string) => {
flushSync(() => maplace.select(id));
card.current?.querySelector<HTMLElement>(toFocus)?.focus();
};
return (
<aside className="venue-card" aria-label="Venue" ref={card}>
{selected?.data === undefined ? (
<div className="venue-picker">
<p
className="venue-list-category"
data-category={shownAlone}
hidden={shownAlone === undefined}
>
{shownAlone}
</p>
<p className="venue-empty">Pick a venue on the map, or here.</p>
<ul className="venue-list" aria-label="Venues">
{listed.map(({ id, title, group }) => (
<li key={id}>
<button
type="button"
className="venue-pick"
data-category={group}
data-id={id}
onClick={() => selectAndFocus(id, ".venue-close")}
>
{title ?? id}
</button>
</li>
))}
</ul>
</div>
) : (
<div className="venue" data-category={selected.group}>
<button
type="button"
className="venue-close"
aria-label="Close"
onClick={() =>
selectAndFocus(undefined, `.venue-pick[data-id="${CSS.escape(selected.id)}"]`)
}
/>
<p className="venue-category">{selected.group}</p>
<h3 className="venue-name">{selected.title}</h3>
<dl>
<div>
<dt>Address</dt>
<dd className="venue-address">{selected.data.address}</dd>
</div>
<div>
<dt>Since</dt>
<dd className="venue-since">{selected.data.since}</dd>
</div>
<div>
<dt>Known for</dt>
<dd className="venue-known-for">{selected.data.knownFor}</dd>
</div>
</dl>
</div>
)}
</aside>
);
}
/** The venues shown, rendered again when they change; read as their ids, so a hover renders none. */
function useListedVenues(): readonly Location[] {
const maplace = useMaplace();
useSyncExternalStore(maplace.subscribe, () =>
listedLocations(maplace.getSnapshot())
.map(({ id }) => id)
.join(),
);
return listedLocations(maplace.getSnapshot());
}
/**
* A chip per category, in the venues' order, showing it alone, or every one again once pressed;
* read from the locations and the category shown alone, so a hover renders nothing.
*/
function EventLegend() {
const maplace = useMaplace();
const locations = useSyncExternalStore(maplace.subscribe, () => maplace.getSnapshot().locations);
const shownAlone = useSyncExternalStore(maplace.subscribe, () =>
shownAloneIn(maplace.getSnapshot()),
);
const categories = new Set(locations.flatMap(({ group }) => group ?? []));
return (
<fieldset className="event-legend" aria-label="Categories">
{[...categories].map((category) => (
<button
key={category}
type="button"
className="category-chip"
data-category={category}
aria-pressed={category === shownAlone}
onClick={() => maplace.setFilter(category === shownAlone ? undefined : [category])}
>
{category}
</button>
))}
</fieldset>
);
}
/** The category the map shows alone, if any. */
function shownAloneIn({ filter }: Snapshot): string | undefined {
const alone = filter?.groups?.length === 1 ? filter.groups[0] : undefined;
return typeof alone === "string" ? alone : undefined;
}
function WhatsOn() {
return (
<MaplaceProvider locations={venues} view={firstView}>
<MaplaceMap createAdapter={createAdapter} className="whats-on-map" markerIcon={markerIcon}>
<MapControl position="bottom-left">
<EventLegend />
</MapControl>
<MapControl position="top-left">
<EventStatus />
</MapControl>
</MaplaceMap>
<VenueCard />
</MaplaceProvider>
);
}
createRoot(document.getElementById("whats-on-maplibre-react-root") as HTMLElement).render(
<StrictMode>
<WhatsOn />
</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/whats-on.css, which every version links. -->
<link rel="stylesheet" href="../styles/whats-on.css">
<div id="whats-on-react-root" class="whats-on"></div>
<script type="module" src="./react.tsx"></script>import { type Location, listedLocations, type Snapshot, type View } from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
import { MapControl, MaplaceMap, MaplaceProvider, useMaplace } from "@maplacejs/maplace/react";
import { StrictMode, useRef, useSyncExternalStore } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
/** What the card beside the map says of a venue, besides its name and category. */
interface VenueDetails {
address: string;
since: number;
knownFor: string;
}
const venues: Location<VenueDetails>[] = [
venue("national-theatre", 51.507, -0.1145, "National Theatre", "Theatre", {
address: "Upper Ground, London SE1 9PX",
since: 1976,
knownFor: "Three stages on the South Bank",
}),
venue("globe", 51.5081, -0.0972, "Shakespeare's Globe", "Theatre", {
address: "21 New Globe Walk, London SE1 9DT",
since: 1997,
knownFor: "An open-air playhouse rebuilt after the 1599 original",
}),
venue("donmar", 51.5136, -0.1254, "Donmar Warehouse", "Theatre", {
address: "41 Earlham Street, London WC2H 9LX",
since: 1977,
knownFor: "A small studio theatre in Covent Garden",
}),
venue("royal-albert-hall", 51.501, -0.1774, "Royal Albert Hall", "Concerts", {
address: "Kensington Gore, London SW7 2AP",
since: 1871,
knownFor: "The BBC Proms, every summer",
}),
venue("wigmore-hall", 51.5165, -0.149, "Wigmore Hall", "Concerts", {
address: "36 Wigmore Street, London W1U 2BP",
since: 1901,
knownFor: "Chamber music and song recitals",
}),
venue("barbican", 51.5202, -0.0938, "Barbican Hall", "Concerts", {
address: "Silk Street, London EC2Y 8DS",
since: 1982,
knownFor: "Home of the London Symphony Orchestra",
}),
venue("borough-market", 51.5055, -0.091, "Borough Market", "Markets", {
address: "8 Southwark Street, London SE1 1TL",
since: 1756,
knownFor: "One of London's oldest food markets",
}),
venue("camden-market", 51.5413, -0.146, "Camden Market", "Markets", {
address: "Camden Lock Place, London NW1 8AF",
since: 1974,
knownFor: "Stalls along the Regent's Canal",
}),
venue("spitalfields", 51.5197, -0.0754, "Old Spitalfields Market", "Markets", {
address: "16 Horner Square, London E1 6EW",
since: 1638,
knownFor: "A Victorian market hall in the East End",
}),
venue("british-library", 51.5299, -0.1277, "British Library", "Talks", {
address: "96 Euston Road, London NW1 2DB",
since: 1973,
knownFor: "The UK's national library, at St Pancras",
}),
venue("conway-hall", 51.5203, -0.1188, "Conway Hall", "Talks", {
address: "25 Red Lion Square, London WC1R 4RL",
since: 1929,
knownFor: "Talks and debates, home of the Conway Hall Ethical Society",
}),
venue("royal-institution", 51.5098, -0.1425, "Royal Institution", "Talks", {
address: "21 Albemarle Street, London W1S 4BS",
since: 1799,
knownFor: "The Christmas Lectures, given since 1825",
}),
];
/** A venue in its category, with what the card says of it. */
function venue(
id: string,
lat: number,
lng: number,
title: string,
group: string,
data: VenueDetails,
): Location<VenueDetails> {
return { id, lat, lng, title, group, data };
}
/**
* Google's map without its map-type, camera and Street View controls: the count and the legend take
* their place.
*/
const createAdapter = () =>
createGoogleAdapter({
mapOptions: { mapTypeControl: false, streetViewControl: false, cameraControl: false },
});
/** Every venue fitted, with room at the edges for the count and the legend over the map. */
const firstView: View = { kind: "fit-all", padding: 80 };
/**
* A pin of your own, its colour the category's (`--category`, by `data-category` in the CSS), in a
* node Maplace.js keeps for each marker and marks `data-hovered` and `data-selected`.
*/
const markerIcon = ({ group }: Location) => <span className="pin" data-category={group} />;
/** The count, and beside it the name of the venue selected, if any. */
function EventStatus() {
return (
<div className="event-status">
<EventCount />
<SelectedName />
</div>
);
}
/** How many venues are shown, of all of them; read as text, so a hover renders nothing. */
function EventCount() {
const maplace = useMaplace();
const text = useSyncExternalStore(maplace.subscribe, () => countText(maplace.getSnapshot()));
return <output className="event-count">{text}</output>;
}
function countText(snapshot: Snapshot): string {
const shown = listedLocations(snapshot).length;
const total = snapshot.locations.length;
return shown === total ? `${total} venues` : `${shown} of ${total} venues`;
}
/**
* The name of the venue selected, marked with its category for its colour; hidden while none is.
* Not a live region: Maplace.js says each selection to a screen reader already.
*/
function SelectedName() {
const maplace = useMaplace<VenueDetails>();
const selected = useSyncExternalStore(maplace.subscribe, () => selectedIn(maplace.getSnapshot()));
return (
<span
className="event-selected"
data-category={selected?.group}
hidden={selected === undefined}
>
{selected?.title}
</span>
);
}
function selectedIn({
locations,
selectedId,
}: Snapshot<VenueDetails>): Location<VenueDetails> | undefined {
return locations.find(({ id }) => id === selectedId);
}
/**
* The card beside the map: the venue selected, its category marked for its colour, with a × closing
* it; or, while none is, the venues shown, each a button selecting it, under the category shown
* alone, if any. A press moves the focus to what takes the button's place, the card rendered at
* once for it. Not a live region: Maplace.js says each selection to a screen reader already.
*/
function VenueCard() {
const maplace = useMaplace<VenueDetails>();
const selected = useSyncExternalStore(maplace.subscribe, () => selectedIn(maplace.getSnapshot()));
const listed = useListedVenues();
const shownAlone = useSyncExternalStore(maplace.subscribe, () =>
shownAloneIn(maplace.getSnapshot()),
);
const card = useRef<HTMLElement>(null);
const selectAndFocus = (id: string | undefined, toFocus: string) => {
flushSync(() => maplace.select(id));
card.current?.querySelector<HTMLElement>(toFocus)?.focus();
};
return (
<aside className="venue-card" aria-label="Venue" ref={card}>
{selected?.data === undefined ? (
<div className="venue-picker">
<p
className="venue-list-category"
data-category={shownAlone}
hidden={shownAlone === undefined}
>
{shownAlone}
</p>
<p className="venue-empty">Pick a venue on the map, or here.</p>
<ul className="venue-list" aria-label="Venues">
{listed.map(({ id, title, group }) => (
<li key={id}>
<button
type="button"
className="venue-pick"
data-category={group}
data-id={id}
onClick={() => selectAndFocus(id, ".venue-close")}
>
{title ?? id}
</button>
</li>
))}
</ul>
</div>
) : (
<div className="venue" data-category={selected.group}>
<button
type="button"
className="venue-close"
aria-label="Close"
onClick={() =>
selectAndFocus(undefined, `.venue-pick[data-id="${CSS.escape(selected.id)}"]`)
}
/>
<p className="venue-category">{selected.group}</p>
<h3 className="venue-name">{selected.title}</h3>
<dl>
<div>
<dt>Address</dt>
<dd className="venue-address">{selected.data.address}</dd>
</div>
<div>
<dt>Since</dt>
<dd className="venue-since">{selected.data.since}</dd>
</div>
<div>
<dt>Known for</dt>
<dd className="venue-known-for">{selected.data.knownFor}</dd>
</div>
</dl>
</div>
)}
</aside>
);
}
/** The venues shown, rendered again when they change; read as their ids, so a hover renders none. */
function useListedVenues(): readonly Location[] {
const maplace = useMaplace();
useSyncExternalStore(maplace.subscribe, () =>
listedLocations(maplace.getSnapshot())
.map(({ id }) => id)
.join(),
);
return listedLocations(maplace.getSnapshot());
}
/**
* A chip per category, in the venues' order, showing it alone, or every one again once pressed;
* read from the locations and the category shown alone, so a hover renders nothing.
*/
function EventLegend() {
const maplace = useMaplace();
const locations = useSyncExternalStore(maplace.subscribe, () => maplace.getSnapshot().locations);
const shownAlone = useSyncExternalStore(maplace.subscribe, () =>
shownAloneIn(maplace.getSnapshot()),
);
const categories = new Set(locations.flatMap(({ group }) => group ?? []));
return (
<fieldset className="event-legend" aria-label="Categories">
{[...categories].map((category) => (
<button
key={category}
type="button"
className="category-chip"
data-category={category}
aria-pressed={category === shownAlone}
onClick={() => maplace.setFilter(category === shownAlone ? undefined : [category])}
>
{category}
</button>
))}
</fieldset>
);
}
/** The category the map shows alone, if any. */
function shownAloneIn({ filter }: Snapshot): string | undefined {
const alone = filter?.groups?.length === 1 ? filter.groups[0] : undefined;
return typeof alone === "string" ? alone : undefined;
}
function WhatsOn() {
return (
<MaplaceProvider locations={venues} view={firstView}>
<MaplaceMap createAdapter={createAdapter} className="whats-on-map" markerIcon={markerIcon}>
<MapControl position="bottom-left">
<EventLegend />
</MapControl>
<MapControl position="top-left">
<EventStatus />
</MapControl>
</MaplaceMap>
<VenueCard />
</MaplaceProvider>
);
}
createRoot(document.getElementById("whats-on-react-root") as HTMLElement).render(
<StrictMode>
<WhatsOn />
</StrictMode>,
);How it works
A map that looks nothing like Maplace.js’s: a dark frame, pins of your own coloured by category, a count over the map, a legend on it whose chips show one category at a time, and beside it a card listing the venues shown, or the one picked. Each piece is one of Maplace.js’s hooks; together they are one idea, the whole look the page’s own.
- HTML: a
<template data-icon>in each<maplace-location>, with itsgroup(Location attributes); the legend a list view of your own,defineListView, atlist-position="bottom-left". The element puts one view of yours on the map, so the count is your own element over the map’s top left, where a control would sit, taking no clicks. The card’s details are each venue’s owndata-attributes, itsdata, read by the page’s script on the store’sselectionChangeinto the card’s<template>, added to the card while a venue is picked (Events); while none is, the card lists the venues shown, fromlistedLocations, each a button callingselect. - Script and Bundler: an
iconnode per location (Icons), and the count and the legend put on the map with the adapter’smountControl, the count rewritten fromlistedLocations, the name beside it from the snapshot’sselectedId, the press moved with the store’s filter as the store changes, and the card written from the venue’sdata(Location fields) onselectionChange, its markup a<template>in the page, and while no venue is, a button per venue shown, rewritten fromlistedLocationswhen they change; a chip callssetFilterwith its category, or with nothing to show them all. - React:
markerIconon<MaplaceMap>, and the count and the legend in two<MapControl>s, reading the store withuseMaplace(), as the card does beside<MaplaceMap>, inside<MaplaceProvider>, its list read as the ids listed so a hover renders nothing, andflushSyncrendering it at once so a press can move the focus into it. - On Google: its map-type, Street View and camera controls are off (
map-optionsin HTML,mapOptionselsewhere), for the clean look, as the MapLibre map shows none either. - In every version: the look is one stylesheet,
whats-on.css, in the examples’styles/folder, which each version’s HTML links, so the page, the script, the bundled and the React versions share it, scoped by the frame’s class,.whats-on, and the map’s,.whats-on-map. Every venue fitted with 80px of padding, clear of the count and the legend: the store’sview,{ kind: "fit-all", padding: 80 }(The first view), or in HTML, which has no attribute for it,fitAllbefore the map opens. Maplace.js’s panel around what goes on the map is made nothing with.maplace-control { padding: 0; background: none; box-shadow: none; }, as its rules weigh nothing (Styling); each category’s colour is one custom property,--category, which its pins and its chip take; the pins’ hovered and selected looks are rules ondata-hoveredanddata-selected, as in HTML markers with CSS states. A venue picked from the card’s list moves the focus to the card’s ×, named “Close”, which takes it back to that venue in the list, so a keyboard never loses its place. The name of the venue picked is a plain element, not a live region: Maplace.js already says each selection to a screen reader (On every map). The pins differ by colour alone, so the chips, named, are how a reader picks a category out.