Bubble map
Cities as bubbles sized by population, a legend, and a count of what is in view.
Map and code
Population 30M 10M 3M
Now in view
Loading the map…
The map couldn't load.
Population
Now in view
Loading the map…
The map couldn't load.
Population
Now in view
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Population 30M 10M 3M
Now in view
Loading the map…
The map couldn't load.
Population
Now in view
Loading the map…
The map couldn't load.
Population
Now in view
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
These maps come from Google Maps and OpenFreeMap, which see your IP address. They stay off until you say so, once for the whole site. What loading the maps sends
Fetches cities.jsonStyled by bubbles.css
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- The world's largest cities as bubbles, each as big as its population, the list beside
it, which "This area" narrows to the map's view, and under the map the legend's sizes and a
count of what it shows. The cities come from cities.json, largest first so the small bubbles
are drawn over the big ones; a bubble's area is its population, Tokyo's 37M is 56px across.
The populations are rounded, for the example. -->
<!-- This example's look lives in the examples' styles/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../../styles/bubbles.css">
<style>
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-maplibre-map { height: 36rem; }
#bubbles-maplibre-map > .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<maplace-map id="bubbles-maplibre-map" list="maplibre-bubbles-cities" list-heading="Cities" list-scope="viewport"
src="/examples/data/cities.json"></maplace-map>
<p class="bubbles-legend">Population
<span class="bubbles-size"><span class="bubble" aria-hidden="true" style="width: 50.4px"></span>30M</span>
<span class="bubbles-size"><span class="bubble" aria-hidden="true" style="width: 29.1px"></span>10M</span>
<span class="bubbles-size"><span class="bubble" aria-hidden="true" style="width: 15.9px"></span>3M</span>
</p>
<p>Now in view <output id="bubbles-maplibre-in-view">–</output></p>
<script>
// The markers, the list's entries and the count under the map, the page's own: defined as the
// page is read, so the map finds them when it opens.
{
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const map = document.getElementById("bubbles-maplibre-map");
// A city's population, from its data in cities.json.
const populationOf = ({ data }) => data.population;
// A city's marker: a circle as big as its population, none under 6px across. Set before the
// map is made (below, by reading map.maplace), which takes it then.
map.markerIcon = (city) => {
const bubble = document.createElement("span");
bubble.className = "bubble";
const diameter = Math.max(6, Math.sqrt(populationOf(city) / 37e6) * 56);
bubble.style.width = bubble.style.height = `${diameter}px`;
return bubble;
};
// A city in the list: its name, then its population.
const cityEntry = ({ location }) => {
const entry = document.createElement("span");
entry.className = "bubbles-city";
const population = document.createElement("span");
population.className = "bubbles-population";
population.textContent = compact.format(populationOf(location));
entry.append(location.title, population);
return entry;
};
Maplace.defineListView("maplibre-bubbles-cities", (maplace, { options }) =>
Maplace.createListView(maplace, { ...options, render: cityEntry }));
// Whether a city is inside the bounds, which may cross the antimeridian (west > east).
const inView = ({ lat, lng }, { north, south, east, west }) => {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
};
// How many cities, and how many people in them: "12 cities · 210M people".
const summaryOf = (cities) => {
const people = cities.reduce((sum, city) => sum + populationOf(city), 0);
return `${cities.length} cities · ${compact.format(people)} people`;
};
// What the map shows, after each move, its first included.
const inViewNow = document.getElementById("bubbles-maplibre-in-view");
map.maplace.on("viewportChange", ({ viewport }) => {
const { locations } = map.maplace.getSnapshot();
if (viewport.bounds) inViewNow.value = summaryOf(locations.filter((city) => inView(city, viewport.bounds)));
});
}
</script><!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- The world's largest cities as bubbles, each as big as its population, the list beside
it, which "This area" narrows to the map's view, and under the map the legend's sizes and a
count of what it shows. The cities come from cities.json, largest first so the small bubbles
are drawn over the big ones; a bubble's area is its population, Tokyo's 37M is 56px across.
The populations are rounded, for the example. -->
<!-- This example's look lives in the examples' styles/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../styles/bubbles.css">
<style>
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-map { height: 36rem; }
#bubbles-map > .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<maplace-map id="bubbles-map" api-key="YOUR_KEY" list="bubbles-cities" list-heading="Cities" list-scope="viewport"
src="/examples/data/cities.json"></maplace-map>
<p class="bubbles-legend">Population
<span class="bubbles-size"><span class="bubble" aria-hidden="true" style="width: 50.4px"></span>30M</span>
<span class="bubbles-size"><span class="bubble" aria-hidden="true" style="width: 29.1px"></span>10M</span>
<span class="bubbles-size"><span class="bubble" aria-hidden="true" style="width: 15.9px"></span>3M</span>
</p>
<p>Now in view <output id="bubbles-in-view">–</output></p>
<script>
// The markers, the list's entries and the count under the map, the page's own: defined as the
// page is read, so the map finds them when it opens.
{
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
const map = document.getElementById("bubbles-map");
// A city's population, from its data in cities.json.
const populationOf = ({ data }) => data.population;
// A city's marker: a circle as big as its population, none under 6px across. Set before the
// map is made (below, by reading map.maplace), which takes it then.
map.markerIcon = (city) => {
const bubble = document.createElement("span");
bubble.className = "bubble";
const diameter = Math.max(6, Math.sqrt(populationOf(city) / 37e6) * 56);
bubble.style.width = bubble.style.height = `${diameter}px`;
return bubble;
};
// A city in the list: its name, then its population.
const cityEntry = ({ location }) => {
const entry = document.createElement("span");
entry.className = "bubbles-city";
const population = document.createElement("span");
population.className = "bubbles-population";
population.textContent = compact.format(populationOf(location));
entry.append(location.title, population);
return entry;
};
Maplace.defineListView("bubbles-cities", (maplace, { options }) =>
Maplace.createListView(maplace, { ...options, render: cityEntry }));
// Whether a city is inside the bounds, which may cross the antimeridian (west > east).
const inView = ({ lat, lng }, { north, south, east, west }) => {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
};
// How many cities, and how many people in them: "12 cities · 210M people".
const summaryOf = (cities) => {
const people = cities.reduce((sum, city) => sum + populationOf(city), 0);
return `${cities.length} cities · ${compact.format(people)} people`;
};
// What the map shows, after each move, its first included.
const inViewNow = document.getElementById("bubbles-in-view");
map.maplace.on("viewportChange", ({ viewport }) => {
const { locations } = map.maplace.getSnapshot();
if (viewport.bounds) inViewNow.value = summaryOf(locations.filter((city) => inView(city, viewport.bounds)));
});
}
</script><!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, what the map and its list mount on, and the map made with Maplace. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- This example's look lives in the examples' styles/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../../styles/bubbles.css">
<style>
#bubbles-maplibre-script-map-and-list { display: flex; height: 24rem; }
#bubbles-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
#bubbles-maplibre-script-list { display: contents; }
#bubbles-maplibre-script-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-maplibre-script-map-and-list { flex-direction: column; height: 36rem; }
#bubbles-maplibre-script-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="bubbles-maplibre-script-map-and-list">
<div id="bubbles-maplibre-script-map"></div>
<div id="bubbles-maplibre-script-list"></div>
</div>
<p class="bubbles-legend" id="bubbles-maplibre-script-legend">Population</p>
<p>Now in view <output id="bubbles-maplibre-script-in-view">–</output></p>
<script type="module">
// Tokyo's 37M, the largest city in the file, is 56px across; a bubble's area is its population.
const LARGEST = 37e6;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
// A circle as big as a population, none under 6px across.
const bubble = (population) => {
const circle = document.createElement("span");
circle.className = "bubble";
const diameter = Math.max(6, Math.sqrt(population / LARGEST) * 56);
circle.style.width = circle.style.height = `${diameter}px`;
return circle;
};
// Whether a city is inside the bounds, which may cross the antimeridian (west > east).
const inView = ({ lat, lng }, { north, south, east, west }) => {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
};
// How many cities, and how many people in them: "12 cities · 210M people".
const summaryOf = (cities) => {
const people = cities.reduce((sum, { data }) => sum + data.population, 0);
return `${cities.length} cities · ${compact.format(people)} people`;
};
// A city in the list: its name, then its population.
const cityEntry = ({ location }) => {
const entry = document.createElement("span");
entry.className = "bubbles-city";
const population = document.createElement("span");
population.className = "bubbles-population";
population.textContent = compact.format(location.data.population);
entry.append(location.title, population);
return entry;
};
const maplace = Maplace.createMapLibreMap("#bubbles-maplibre-script-map", {
view: { kind: "fit-all", padding: 32 },
list: { container: "#bubbles-maplibre-script-list", heading: "Cities", scope: "viewport", render: cityEntry },
});
// The legend's sizes, drawn as the bubbles are.
for (const population of [30e6, 10e6, 3e6]) {
const size = document.createElement("span");
size.className = "bubbles-size";
const circle = bubble(population);
circle.setAttribute("aria-hidden", "true");
size.append(circle, compact.format(population));
document.getElementById("bubbles-maplibre-script-legend").append(size);
}
// The file lists the largest first, so the small bubbles are drawn over the big ones.
const cities = await fetch("/examples/data/cities.json").then((response) => response.json());
maplace.setLocations(cities.map((city) => ({ ...city, icon: () => bubble(city.data.population) })));
// What the map shows: now, if it has settled while the file loaded, then after each move.
const inViewNow = document.getElementById("bubbles-maplibre-script-in-view");
const showInView = (bounds) => {
if (bounds) inViewNow.value = summaryOf(cities.filter((city) => inView(city, bounds)));
};
showInView(maplace.getSnapshot().viewport?.bounds);
maplace.on("viewportChange", ({ viewport }) => showInView(viewport.bounds));
</script><!doctype html>
<!-- A page of your own script: the CDN script, what the map and its list mount on, and the map made with Maplace, which adds Maps JS with your key. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- This example's look lives in the examples' styles/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../styles/bubbles.css">
<style>
#bubbles-script-map-and-list { display: flex; height: 24rem; }
#bubbles-script-map { flex: 1 1 auto; min-width: 0; }
#bubbles-script-list { display: contents; }
#bubbles-script-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-script-map-and-list { flex-direction: column; height: 36rem; }
#bubbles-script-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="bubbles-script-map-and-list">
<div id="bubbles-script-map"></div>
<div id="bubbles-script-list"></div>
</div>
<p class="bubbles-legend" id="bubbles-script-legend">Population</p>
<p>Now in view <output id="bubbles-script-in-view">–</output></p>
<script type="module">
// Tokyo's 37M, the largest city in the file, is 56px across; a bubble's area is its population.
const LARGEST = 37e6;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
// A circle as big as a population, none under 6px across.
const bubble = (population) => {
const circle = document.createElement("span");
circle.className = "bubble";
const diameter = Math.max(6, Math.sqrt(population / LARGEST) * 56);
circle.style.width = circle.style.height = `${diameter}px`;
return circle;
};
// Whether a city is inside the bounds, which may cross the antimeridian (west > east).
const inView = ({ lat, lng }, { north, south, east, west }) => {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
};
// How many cities, and how many people in them: "12 cities · 210M people".
const summaryOf = (cities) => {
const people = cities.reduce((sum, { data }) => sum + data.population, 0);
return `${cities.length} cities · ${compact.format(people)} people`;
};
// A city in the list: its name, then its population.
const cityEntry = ({ location }) => {
const entry = document.createElement("span");
entry.className = "bubbles-city";
const population = document.createElement("span");
population.className = "bubbles-population";
population.textContent = compact.format(location.data.population);
entry.append(location.title, population);
return entry;
};
const maplace = Maplace.createGoogleMap("#bubbles-script-map", {
apiKey: "YOUR_KEY",
view: { kind: "fit-all", padding: 32 },
list: { container: "#bubbles-script-list", heading: "Cities", scope: "viewport", render: cityEntry },
});
// The legend's sizes, drawn as the bubbles are.
for (const population of [30e6, 10e6, 3e6]) {
const size = document.createElement("span");
size.className = "bubbles-size";
const circle = bubble(population);
circle.setAttribute("aria-hidden", "true");
size.append(circle, compact.format(population));
document.getElementById("bubbles-script-legend").append(size);
}
// The file lists the largest first, so the small bubbles are drawn over the big ones.
const cities = await fetch("/examples/data/cities.json").then((response) => response.json());
maplace.setLocations(cities.map((city) => ({ ...city, icon: () => bubble(city.data.population) })));
// What the map shows: now, if it has settled while the file loaded, then after each move.
const inViewNow = document.getElementById("bubbles-script-in-view");
const showInView = (bounds) => {
if (bounds) inViewNow.value = summaryOf(cities.filter((city) => inView(city, bounds)));
};
showInView(maplace.getSnapshot().viewport?.bounds);
maplace.on("viewportChange", ({ viewport }) => showInView(viewport.bounds));
</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/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../../styles/bubbles.css">
<style>
#bubbles-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
#bubbles-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
#bubbles-maplibre-vanilla-list { display: contents; }
#bubbles-maplibre-vanilla-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-maplibre-vanilla-map-and-list { flex-direction: column; height: 36rem; }
#bubbles-maplibre-vanilla-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="bubbles-maplibre-vanilla-map-and-list">
<div id="bubbles-maplibre-vanilla-map"></div>
<div id="bubbles-maplibre-vanilla-list"></div>
</div>
<p class="bubbles-legend" id="bubbles-maplibre-vanilla-legend">Population</p>
<p>Now in view <output id="bubbles-maplibre-vanilla-in-view">–</output></p>
<script type="module" src="./vanilla.ts"></script>import "maplibre-gl/dist/maplibre-gl.css";
import type { Bounds, ListEntry, Location, MarkerLocation } from "@maplacejs/maplace";
import { createMapLibreMap } from "@maplacejs/maplace/maplibre";
/** What a city's bubble and entry show. */
interface City {
readonly population: number;
}
// Tokyo's 37M, the largest city in the file, is 56px across; a bubble's area is its population.
const LARGEST = 37e6;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
/** A circle as big as `population`, none under 6px across. */
function bubble(population: number): HTMLElement {
const circle = document.createElement("span");
circle.className = "bubble";
const diameter = Math.max(6, Math.sqrt(population / LARGEST) * 56);
circle.style.width = circle.style.height = `${diameter}px`;
return circle;
}
/** A city in the list: its name, then its population. */
function cityEntry({ location }: ListEntry<City>): Node {
const entry = document.createElement("span");
entry.className = "bubbles-city";
const population = document.createElement("span");
population.className = "bubbles-population";
population.textContent = compact.format(location.data?.population ?? 0);
entry.append(location.title ?? "", population);
return entry;
}
/** Whether `city` is inside `bounds`, which may cross the antimeridian (`west > east`). */
function inView({ lat, lng }: MarkerLocation<City>, { north, south, east, west }: Bounds): boolean {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
}
/** How many cities, and how many people in them: "12 cities · 210M people". */
function summaryOf(cities: readonly Location<City>[]): string {
const people = cities.reduce((sum, { data }) => sum + (data?.population ?? 0), 0);
return `${cities.length} cities · ${compact.format(people)} people`;
}
const maplace = createMapLibreMap<City>("#bubbles-maplibre-vanilla-map", {
view: { kind: "fit-all", padding: 32 },
list: {
container: "#bubbles-maplibre-vanilla-list",
heading: "Cities",
scope: "viewport",
render: cityEntry,
},
});
// The legend's sizes, drawn as the bubbles are.
for (const population of [30e6, 10e6, 3e6]) {
const size = document.createElement("span");
size.className = "bubbles-size";
const circle = bubble(population);
circle.setAttribute("aria-hidden", "true");
size.append(circle, compact.format(population));
document.querySelector("#bubbles-maplibre-vanilla-legend")?.append(size);
}
// The file lists the largest first, so the small bubbles are drawn over the big ones.
const cities: MarkerLocation<City>[] = await (await fetch("/examples/data/cities.json")).json();
maplace.setLocations(
cities.map((city) => ({ ...city, icon: () => bubble(city.data?.population ?? 0) })),
);
// What the map shows: now, if it has settled while the file loaded, then after each move.
const inViewNow = document.querySelector<HTMLOutputElement>("#bubbles-maplibre-vanilla-in-view");
function showInView(bounds: Bounds | undefined): void {
if (inViewNow && bounds)
inViewNow.value = summaryOf(cities.filter((city) => inView(city, bounds)));
}
showInView(maplace.getSnapshot().viewport?.bounds);
maplace.on("viewportChange", ({ viewport }) => showInView(viewport.bounds));<!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/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../styles/bubbles.css">
<style>
#bubbles-vanilla-map-and-list { display: flex; height: 24rem; }
#bubbles-vanilla-map { flex: 1 1 auto; min-width: 0; }
#bubbles-vanilla-list { display: contents; }
#bubbles-vanilla-list .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-vanilla-map-and-list { flex-direction: column; height: 36rem; }
#bubbles-vanilla-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="bubbles-vanilla-map-and-list">
<div id="bubbles-vanilla-map"></div>
<div id="bubbles-vanilla-list"></div>
</div>
<p class="bubbles-legend" id="bubbles-vanilla-legend">Population</p>
<p>Now in view <output id="bubbles-vanilla-in-view">–</output></p>
<script type="module" src="./vanilla.ts"></script>import type { Bounds, ListEntry, Location, MarkerLocation } from "@maplacejs/maplace";
import { createGoogleMap } from "@maplacejs/maplace/google";
/** What a city's bubble and entry show. */
interface City {
readonly population: number;
}
// Tokyo's 37M, the largest city in the file, is 56px across; a bubble's area is its population.
const LARGEST = 37e6;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
/** A circle as big as `population`, none under 6px across. */
function bubble(population: number): HTMLElement {
const circle = document.createElement("span");
circle.className = "bubble";
const diameter = Math.max(6, Math.sqrt(population / LARGEST) * 56);
circle.style.width = circle.style.height = `${diameter}px`;
return circle;
}
/** A city in the list: its name, then its population. */
function cityEntry({ location }: ListEntry<City>): Node {
const entry = document.createElement("span");
entry.className = "bubbles-city";
const population = document.createElement("span");
population.className = "bubbles-population";
population.textContent = compact.format(location.data?.population ?? 0);
entry.append(location.title ?? "", population);
return entry;
}
/** Whether `city` is inside `bounds`, which may cross the antimeridian (`west > east`). */
function inView({ lat, lng }: MarkerLocation<City>, { north, south, east, west }: Bounds): boolean {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
}
/** How many cities, and how many people in them: "12 cities · 210M people". */
function summaryOf(cities: readonly Location<City>[]): string {
const people = cities.reduce((sum, { data }) => sum + (data?.population ?? 0), 0);
return `${cities.length} cities · ${compact.format(people)} people`;
}
const maplace = createGoogleMap<City>("#bubbles-vanilla-map", {
view: { kind: "fit-all", padding: 32 },
list: {
container: "#bubbles-vanilla-list",
heading: "Cities",
scope: "viewport",
render: cityEntry,
},
});
// The legend's sizes, drawn as the bubbles are.
for (const population of [30e6, 10e6, 3e6]) {
const size = document.createElement("span");
size.className = "bubbles-size";
const circle = bubble(population);
circle.setAttribute("aria-hidden", "true");
size.append(circle, compact.format(population));
document.querySelector("#bubbles-vanilla-legend")?.append(size);
}
// The file lists the largest first, so the small bubbles are drawn over the big ones.
const cities: MarkerLocation<City>[] = await (await fetch("/examples/data/cities.json")).json();
maplace.setLocations(
cities.map((city) => ({ ...city, icon: () => bubble(city.data?.population ?? 0) })),
);
// What the map shows: now, if it has settled while the file loaded, then after each move.
const inViewNow = document.querySelector<HTMLOutputElement>("#bubbles-vanilla-in-view");
function showInView(bounds: Bounds | undefined): void {
if (inViewNow && bounds)
inViewNow.value = summaryOf(cities.filter((city) => inView(city, bounds)));
}
showInView(maplace.getSnapshot().viewport?.bounds);
maplace.on("viewportChange", ({ viewport }) => showInView(viewport.bounds));<!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/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../../styles/bubbles.css">
<style>
#bubbles-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
#bubbles-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
#bubbles-maplibre-react-root .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-maplibre-react-root .map-and-list { flex-direction: column; height: 36rem; }
#bubbles-maplibre-react-root .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="bubbles-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>import "maplibre-gl/dist/maplibre-gl.css";
import type { Bounds, ListEntry, Location, MarkerLocation } from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
/** What a city's bubble and entry show. */
interface City {
readonly population: number;
}
const FIRST_VIEW = { kind: "fit-all", padding: 32 } as const;
// Tokyo's 37M, the largest city in the file, is 56px across; a bubble's area is its population.
const LARGEST = 37e6;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
/** Whether `city` is inside `bounds`, which may cross the antimeridian (`west > east`). */
function inView({ lat, lng }: MarkerLocation<City>, { north, south, east, west }: Bounds): boolean {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
}
/** How many cities, and how many people in them: "12 cities · 210M people". */
function summaryOf(cities: readonly Location<City>[]): string {
const people = cities.reduce((sum, { data }) => sum + (data?.population ?? 0), 0);
return `${cities.length} cities · ${compact.format(people)} people`;
}
/** A circle as big as `population`, none under 6px across. */
function Bubble({ population }: { readonly population: number }) {
const diameter = Math.max(6, Math.sqrt(population / LARGEST) * 56);
return <span className="bubble" style={{ width: diameter, height: diameter }} />;
}
const markerIcon = ({ data }: Location<City>) => <Bubble population={data?.population ?? 0} />;
/** A city in the list: its name, then its population. */
const cityEntry = ({ location }: ListEntry<City>) => (
<span className="bubbles-city">
{location.title}
<span className="bubbles-population">{compact.format(location.data?.population ?? 0)}</span>
</span>
);
function Bubbles() {
// The file lists the largest first, so the small bubbles are drawn over the big ones.
const [cities, setCities] = useState<readonly MarkerLocation<City>[]>([]);
const [bounds, setBounds] = useState<Bounds>();
useEffect(() => {
fetch("/examples/data/cities.json")
.then((response) => response.json())
.then(setCities);
}, []);
return (
<MaplaceProvider
locations={cities}
view={FIRST_VIEW}
onViewportChange={({ viewport }) => setBounds(viewport.bounds)}
>
<div className="map-and-list">
<MaplaceMap createAdapter={createMapLibreAdapter} className="map" markerIcon={markerIcon} />
<LocationList heading="Cities" scope="viewport">
{cityEntry}
</LocationList>
</div>
<p className="bubbles-legend">
Population
{[30e6, 10e6, 3e6].map((population) => (
<span key={population} className="bubbles-size">
<span aria-hidden="true">
<Bubble population={population} />
</span>
{compact.format(population)}
</span>
))}
</p>
<p>
Now in view{" "}
<output>{bounds ? summaryOf(cities.filter((city) => inView(city, bounds))) : "–"}</output>
</p>
</MaplaceProvider>
);
}
createRoot(document.getElementById("bubbles-maplibre-react-root") as HTMLElement).render(
<StrictMode>
<Bubbles />
</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/bubbles.css, which every version links. -->
<link rel="stylesheet" href="../styles/bubbles.css">
<style>
#bubbles-react-root .map-and-list { display: flex; height: 24rem; }
#bubbles-react-root .map { flex: 1 1 auto; min-width: 0; }
#bubbles-react-root .maplace-list-view { flex: 0 1 16rem; }
/* On a phone the list goes under the map, its half staying that size. */
@media (width < 40rem) {
#bubbles-react-root .map-and-list { flex-direction: column; height: 36rem; }
#bubbles-react-root .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
}
</style>
<div id="bubbles-react-root"></div>
<script type="module" src="./react.tsx"></script>import type { Bounds, ListEntry, Location, MarkerLocation } from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
/** What a city's bubble and entry show. */
interface City {
readonly population: number;
}
const FIRST_VIEW = { kind: "fit-all", padding: 32 } as const;
// Tokyo's 37M, the largest city in the file, is 56px across; a bubble's area is its population.
const LARGEST = 37e6;
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
/** Whether `city` is inside `bounds`, which may cross the antimeridian (`west > east`). */
function inView({ lat, lng }: MarkerLocation<City>, { north, south, east, west }: Bounds): boolean {
const inLongitude = west <= east ? lng >= west && lng <= east : lng >= west || lng <= east;
return lat >= south && lat <= north && inLongitude;
}
/** How many cities, and how many people in them: "12 cities · 210M people". */
function summaryOf(cities: readonly Location<City>[]): string {
const people = cities.reduce((sum, { data }) => sum + (data?.population ?? 0), 0);
return `${cities.length} cities · ${compact.format(people)} people`;
}
/** A circle as big as `population`, none under 6px across. */
function Bubble({ population }: { readonly population: number }) {
const diameter = Math.max(6, Math.sqrt(population / LARGEST) * 56);
return <span className="bubble" style={{ width: diameter, height: diameter }} />;
}
const markerIcon = ({ data }: Location<City>) => <Bubble population={data?.population ?? 0} />;
/** A city in the list: its name, then its population. */
const cityEntry = ({ location }: ListEntry<City>) => (
<span className="bubbles-city">
{location.title}
<span className="bubbles-population">{compact.format(location.data?.population ?? 0)}</span>
</span>
);
function Bubbles() {
// The file lists the largest first, so the small bubbles are drawn over the big ones.
const [cities, setCities] = useState<readonly MarkerLocation<City>[]>([]);
const [bounds, setBounds] = useState<Bounds>();
useEffect(() => {
fetch("/examples/data/cities.json")
.then((response) => response.json())
.then(setCities);
}, []);
return (
<MaplaceProvider
locations={cities}
view={FIRST_VIEW}
onViewportChange={({ viewport }) => setBounds(viewport.bounds)}
>
<div className="map-and-list">
<MaplaceMap createAdapter={createGoogleAdapter} className="map" markerIcon={markerIcon} />
<LocationList heading="Cities" scope="viewport">
{cityEntry}
</LocationList>
</div>
<p className="bubbles-legend">
Population
{[30e6, 10e6, 3e6].map((population) => (
<span key={population} className="bubbles-size">
<span aria-hidden="true">
<Bubble population={population} />
</span>
{compact.format(population)}
</span>
))}
</p>
<p>
Now in view{" "}
<output>{bounds ? summaryOf(cities.filter((city) => inView(city, bounds))) : "–"}</output>
</p>
</MaplaceProvider>
);
}
createRoot(document.getElementById("bubbles-react-root") as HTMLElement).render(
<StrictMode>
<Bubbles />
</StrictMode>,
);How it works
The world’s largest cities as bubbles, each as big as its population, the list beside the map, which “This area” narrows to the map’s view, and under the map the legend’s sizes and a count of what it shows. The populations are rounded and approximate, for the example.
- HTML:
srcnamescities.json(Data), and the page’s script setsmarkerIcon, which sizes each city’s bubble from itsdata.population(Properties and methods);list-scope="viewport"puts the “All” and “This area” switch above the list (Map attributes), a list view of the page’s own reads each population from the location’sdata(List views), and aviewportChangelistener counts what is in view. - Script and Bundler: the cities come from
cities.json; each bubble is the city’sicon, a circle sized in pixels against the largest city’s population, so the legend’s sizes hold at every zoom (Icons);list: { scope: "viewport", render }(List view options), and aviewportChangelistener counts the cities in the map’s bounds (Events). - React:
markerIconon<MaplaceMap>,<LocationList scope="viewport">, andonViewportChangeon<MaplaceProvider>into state (Event props). - Note: the cities are listed largest first, and a marker added later is drawn over one before it, so the small bubbles stay on top and can be clicked.