import { Pins, Points, Reactive, Svg } from "@visquill/visquill-gdk";
import { EUROPE, cities } from "./cities";
import { createMap } from "./map";
import "./styles.css";

// Part 6: size by zoom.
export function run(div: HTMLDivElement) {
  const { map, rvg, toScreen, toGeo, trackHandle } = createMap(div, "map-", EUROPE[0], EUROPE[1]);
  const canvas = rvg.canvas;

  ["a", "b", "c"].forEach((key, i) => {
    canvas.visuals.box(`bar ${key}`, { x: 12 + i * 26, y: 12 }, { x: 20 + i * 26, y: 20 });
    const label = canvas.text.label(key, "legend");
    Points.copy({ x: 24 + i * 26, y: 20 }, label);
  });
  const note = canvas.text.label("made-up values", "legend");
  Points.copy({ x: 92, y: 20 }, note);

  // A layer per city: baseline, bars and name around its origin.
  const layers = cities.map((city) => {
    const layer = canvas.layer();
    layer.visuals.segment("baseline", { x: -12, y: 0 }, { x: 12, y: 0 });
    city.values.forEach((value, i) => {
      const left = -10 + i * 7;
      layer.visuals.box(`bar ${"abc"[i]}`, { x: left, y: -value * 0.35 }, { x: left + 6, y: 0 });
    });
    const label = layer.text.label(city.name, "name");
    Points.copy({ x: 0, y: 12 }, label);
    return layer;
  });

  // The handle has a place on the map, in geographic coordinates.
  canvas.handles.defaultZIndex = 1;
  let place = { lng: 8, lat: 47 };
  const handle = canvas.handles.disk("handle");
  const readout = canvas.text.label("", "readout");
  trackHandle(handle);

  // The zoom at the start. The charts have their normal size there.
  const startZoom = map.getZoom();

  map.on("render", () => {
    Reactive.block(() => {
      // The anchor is a pin. Its direction is the layer's x-axis, and its
      // length scales the layer: (1, 0) is the normal size, (2, 0) twice as
      // large. Two zoom levels in make the map four times as large and the
      // charts twice as large, between 0.6 and 2 times their size.
      const scale = Math.min(2, Math.max(0.6, 2 ** ((map.getZoom() - startZoom) / 2)));
      cities.forEach((city, i) => {
        Pins.withOrientation(toScreen(city), { x: scale, y: 0 }, layers[i].anchor);
      });
      if (!handle.active.value) Points.copy(toScreen(place), handle);
    });
  });

  Reactive.do([handle], () => {
    if (handle.active.value) place = toGeo(handle);

    readout.value = `${place.lat.toFixed(2)}° N  ${place.lng.toFixed(2)}° E`;
    Points.moveRight(handle, 14, readout);

    const distances = cities.map((city) => Points.distanceToPoint(handle, toScreen(city)).value);
    const nearest = distances.indexOf(Math.min(...distances));
    layers.forEach((layer, i) => Svg.get(layer).classList.toggle("map-near", i === nearest));
  });

  return () => map.remove();
}
import { Map, setWorkerUrl } from "maplibre-gl";
import workerUrl from "maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url";
import "maplibre-gl/dist/maplibre-gl.css";
import { VisQuill, Reactive, Svg, type RvgHandle } from "@visquill/visquill-gdk";

// MapLibre reads its tiles in a web worker. Vite cannot find the worker
// file on its own, so its URL is set here once.
setWorkerUrl(workerUrl);

export interface GeoPoint {
  lng: number;
  lat: number;
}

/** A MapLibre map with a VisQuill graphic on top of it. The map shows the
 *  area between the two corners (south-west and north-east). */
export function createMap(div: HTMLDivElement, cssPrefix: string, southWest: GeoPoint, northEast: GeoPoint) {
  // Two divs on top of each other: the map below, the graphic above.
  div.style.position = "relative";
  const mapDiv = document.createElement("div");
  const graphicDiv = document.createElement("div");
  mapDiv.style.cssText = "position: absolute; inset: 0";
  graphicDiv.style.cssText = "position: absolute; inset: 0";
  div.append(mapDiv, graphicDiv);

  const map = new Map({
    container: mapDiv,
    style: "https://tiles.openfreemap.org/styles/positron",
    bounds: [southWest, northEast],
    fitBoundsOptions: { padding: 20 },
  });
  const rvg = VisQuill.create(graphicDiv, cssPrefix);

  // The base map has its own place names. The graphic draws its own, so
  // the map's labels (its "symbol" layers) are hidden once the style is loaded.
  map.on("style.load", () => {
    for (const layer of map.getStyle().layers) {
      if (layer.type === "symbol") map.setLayoutProperty(layer.id, "visibility", "none");
    }
  });

  // The graphic lies on top, so it would catch every click and drag. With
  // pointer-events "none", all input goes through to the map. Visuals that
  // should react to the pointer turn it back on in CSS.
  graphicDiv.style.pointerEvents = "none";
  const svg = Svg.get(rvg);

  // From geographic coordinates to pixels in the graphic, and back. The
  // result changes whenever the map is panned or zoomed.
  const toScreen = (p: GeoPoint) => map.project(p);
  const toGeo = (p: { x: number; y: number }): GeoPoint => map.unproject([p.x, p.y]);

  // While a handle is dragged, the graphic must receive the pointer moves
  // everywhere, not only over the handle. Otherwise the drag stops as soon
  // as the pointer leaves the handle.
  function trackHandle(handle: RvgHandle) {
    Reactive.do([handle.active], () => {
      svg.style.pointerEvents = handle.active.value ? "all" : "";
    }, false);
  }

  return { map, rvg, toScreen, toGeo, trackHandle };
}
import type { GeoPoint } from "./map";

/** The area the map shows: south-west and north-east corner. */
export const EUROPE: [GeoPoint, GeoPoint] = [{ lng: -11, lat: 36 }, { lng: 26, lat: 61 }];

// Fourteen European capitals. The coordinates are real; the three values
// per city (a, b, c, each from 0 to 100) are made up for this tutorial.
export interface City extends GeoPoint {
  name: string;
  values: [number, number, number];
}

export const cities: City[] = [
  { name: "Lisbon", lng: -9.14, lat: 38.72, values: [62, 25, 48] },
  { name: "Madrid", lng: -3.7, lat: 40.42, values: [45, 70, 30] },
  { name: "Dublin", lng: -6.26, lat: 53.35, values: [30, 40, 85] },
  { name: "Paris", lng: 2.35, lat: 48.86, values: [80, 55, 35] },
  { name: "Amsterdam", lng: 4.9, lat: 52.37, values: [90, 30, 50] },
  { name: "Berlin", lng: 13.4, lat: 52.52, values: [55, 85, 40] },
  { name: "Copenhagen", lng: 12.57, lat: 55.68, values: [75, 45, 65] },
  { name: "Stockholm", lng: 18.07, lat: 59.33, values: [35, 60, 90] },
  { name: "Prague", lng: 14.42, lat: 50.08, values: [50, 35, 55] },
  { name: "Vienna", lng: 16.37, lat: 48.21, values: [65, 75, 25] },
  { name: "Warsaw", lng: 21.01, lat: 52.23, values: [40, 50, 70] },
  { name: "Budapest", lng: 19.04, lat: 47.5, values: [70, 30, 45] },
  { name: "Rome", lng: 12.5, lat: 41.9, values: [25, 65, 60] },
  { name: "Athens", lng: 23.73, lat: 37.98, values: [55, 40, 80] },
];
/* Each class is the prefix "map-" plus the name used in demo.ts. */

/* Part 1: a point fixed in the middle of the graphic. */
.map-center { r: 6px; fill: none; stroke: #1c1a17; stroke-width: 2px; }

.map-dot { r: 4px; fill: #1c1a17; }
.map-name {
  fill: #1c1a17;
  font: 600 11px Inter, system-ui, sans-serif;
  text-anchor: middle;
  paint-order: stroke;
  stroke: #faf6ef;
  stroke-width: 3px;
}

/* Part 4: legend, baseline and bars. */
.map-legend {
  fill: #6b645a;
  font: 500 11px "JetBrains Mono", ui-monospace, monospace;
}
.map-baseline { stroke: #1c1a17; stroke-width: 1px; }
.map-bar { stroke: #faf6ef; stroke-width: 0.5px; }
.map-a { fill: #3d6fa8; }
.map-b { fill: #d8913a; }
.map-c { fill: #3f7a5b; }

/* Part 5: the handle, its readout and the nearest city. */
.map-handle {
  r: 8px;
  fill: #c0503f;
  stroke: #faf6ef;
  stroke-width: 2px;
  pointer-events: auto;
  cursor: grab;
}
.map-readout {
  fill: #1c1a17;
  font: 500 11px "JetBrains Mono", ui-monospace, monospace;
  dominant-baseline: middle;
  paint-order: stroke;
  stroke: #faf6ef;
  stroke-width: 3px;
}
.map-near .map-name { fill: #c0503f; }
.map-near .map-baseline { stroke: #c0503f; stroke-width: 2px; }

Tutorial · 6 parts

VisQuill on a map

Charts on a MapLibre map: placing graphics at coordinates, bars per city, a draggable handle and charts that scale with the zoom.

01

What you will build

A map of Europe with a small bar chart for each of fourteen capitals. The charts stay on their cities while the map is panned and zoomed, and grow when you zoom in. A red handle can be dragged to any place; it shows its coordinates and highlights the nearest city. The values are made up.

This is the result of the last part. Pan, zoom and drag the handle.

02

What you will learn

  • Putting a VisQuill graphic on top of a MapLibre map: a small adapter of about 50 lines that you write yourself.
  • Letting pointer input through to the map, and catching it while a handle is dragged.
  • Turning coordinates into pixels on every render, and pixels back into coordinates.
  • One layer per city: only the anchors move.
  • Scaling layers through their anchor.

The base map comes from OpenFreeMap and needs an internet connection. It helps to know the basics from the clock tutorial.

03

How the parts work

Each part adds to the code of the part before it. On the right are the live demo and its code; as you scroll through a part, the code and the visuals the text is about are highlighted. Every part can be downloaded as a small Vite project that runs on its own.

Start with part 1: Map and graphic →