Declutter

City labels shown by zoom level

The places of Europe with labels that appear as you zoom in, larger places first. Declutter.boxes computes once at which zoom each label fits.

// Demonstrates Declutter.boxes: the places of Europe from Natural Earth,
// drawn as dots in a zoomable map projection, each with a label right of
// its dot. Declutter.boxes computes once, for every label, the smallest
// zoom at which it is shown so that no two shown labels overlap; larger
// places come first. A viewport takes care of panning and zooming; the
// dots and labels keep their size, so they are drawn in a layer above it
// at the viewport's zoom. Zooming only compares the zoom with each
// label's number, and a pan only moves the layer.

import { VisQuill, Reactive, Boxes, Segments, Points, Circles, Declutter, Viewports, type Box } from "@visquill/visquill-gdk"
import { places } from "./places"
import "./styles.css"

// ─── Layout ───────────────────────────────────────────────────────────────
const referenceZoom = 3      // the zoom of the world coordinates
const startZoom     = 4
const minZoom       = 3
const maxZoom       = 10
const labelHeight   = 14     // text height of the labels (12px font)
const labelGap      = 5      // from the dot to the start of its label, px
const padding       = 4      // gap between two shown labels; covers the dot left of a box
const dotRadius     = 2.5
const margin        = 150    // places this far outside the view are drawn too, px

// Web Mercator, as in web maps: x and y from 0 to 1. At zoom z the whole
// world is 256 × 2^z pixels wide.
const mercator = (lon: number, lat: number) => {
    const phi = lat * Math.PI / 180
    return { x: (lon + 180) / 360, y: (1 - Math.log(Math.tan(Math.PI / 4 + phi / 2)) / Math.PI) / 2 }
}
const worldSize = (zoom: number) => 256 * 2 ** zoom

export function run(div: HTMLDivElement) {
    const rvg    = VisQuill.create(div, "demos-declutter-city-labels-")
    const canvas = rvg.canvas

    // ─── The view: a viewport over the whole frame ────────────────────
    // World coordinates are pixels at the reference zoom. The viewport's
    // zoom is 2^(z - referenceZoom) at map zoom z.
    const view  = canvas.viewports.box({ panning: true, zooming: true })
    const start = mercator(12, 52)
    Reactive.do([rvg.frame], () => {
        Boxes.copy(rvg.frame, view.boundary)
        Viewports.zoomTo(Viewports.reset(view.origin), 2 ** (startZoom - referenceZoom), [0, 0], view.origin)
        Viewports.panPointTo(view.origin, { x: start.x * worldSize(referenceZoom), y: start.y * worldSize(referenceZoom) },
            Boxes.center(rvg.frame), view.origin)
    })

    // ─── A dot and a label per place, in a layer above the viewport ───
    const map    = view.frame.layer()
    const at     = places.map(([, lon, lat]) => {
        const m = mercator(lon, lat)
        return { x: m.x * worldSize(referenceZoom), y: m.y * worldSize(referenceZoom) }
    })
    const dots   = places.map(p => map.visuals.circle(p[4] ? "capital-dot" : "dot"))
    const labels = places.map(p => map.text.label(p[0], p[4] ? "capital" : "label"))

    // ─── A panel over the sea west of Scotland: instructions, zoom, source
    // Created after the places, so it covers them.
    const panel        = canvas.visuals.box("panel")
    const instructions = canvas.text.label("Scroll to zoom · drag to pan", "instructions")
    const zoomLabel    = canvas.text.label("", "zoom")
    const source       = canvas.text.label("Places: Natural Earth (public domain)", "source")
    Reactive.do([rvg.frame], () => {
        Boxes.box(Points.move(Segments.midPoint(Boxes.leftSide(rvg.frame)), 12, -175), 250, 74, panel)
        Points.move(Segments.midPoint(Boxes.leftSide(rvg.frame)), 24, -157, instructions)
        Points.move(Segments.midPoint(Boxes.leftSide(rvg.frame)), 24, -135, zoomLabel)
        Points.move(Segments.midPoint(Boxes.leftSide(rvg.frame)), 24, -115, source)
    })

    // ─── Declutter: once ──────────────────────────────────────────────
    // Each label as a box in world coordinates, from its dot to the end of
    // its text. The viewport's zoom scales the positions while the labels
    // keep their size: that is Declutter's scale.
    const boxes: Box[] = places.map((_, i) =>
        Boxes.box({ x: at[i].x, y: at[i].y - labelHeight / 2 },
            labelGap + Boxes.width(labels[i].extent).value, labelHeight))
    // anchor [0, 0.5]: the middle of the box's left side stays at the dot.
    const minScale = Declutter.boxes(boxes, places.map(p => p[3]), { padding, anchor: [0, 0.5] })

    // ─── Draw the view ────────────────────────────────────────────────
    // A place is drawn while it is in the view (with a margin around the
    // frame), its label only once the zoom has reached the label's scale.
    // Hidden visuals stay in the DOM with display: none. A pan moves the
    // layer; only when it has moved by more than the margin since the last
    // draw, or the zoom has changed, are the places drawn again, relative
    // to where the layer is.
    let drawnZoom   = 0
    let drawnPan    = { x: 0, y: 0 }
    let drawnAnchor = { x: 0, y: 0 }
    const draw = (zoom: number, pan: { x: number, y: number }) => {
        drawnZoom   = zoom
        drawnPan    = pan
        drawnAnchor = { x: map.anchor.x, y: map.anchor.y }
        const left   = Boxes.left(rvg.frame).value - 200 - margin
        const right  = Boxes.right(rvg.frame).value + margin
        const top    = Boxes.top(rvg.frame).value - 20 - margin
        const bottom = Boxes.bottom(rvg.frame).value + 20 + margin
        places.forEach((_, i) => {
            const s      = { x: at[i].x * zoom + pan.x, y: at[i].y * zoom + pan.y }
            const p      = { x: s.x - map.anchor.x, y: s.y - map.anchor.y }
            const inView = s.x > left && s.x < right && s.y > top && s.y < bottom
            dots[i].visible.value   = inView
            labels[i].visible.value = inView && zoom >= minScale[i]
            if (!inView) return
            Circles.circleAt(p, dotRadius, dots[i])
            if (labels[i].visible.value) Points.move(p, labelGap, 0, labels[i])
        })
        zoomLabel.value = `zoom ${(referenceZoom + Math.log2(zoom)).toFixed(1)}`
    }
    Reactive.do([rvg.frame, view.origin], () => {
        // Keep the zoom between minZoom and maxZoom.
        const zoom = Math.min(2 ** (maxZoom - referenceZoom), Math.max(2 ** (minZoom - referenceZoom),
            Viewports.getZoom(view.origin).value))
        if (zoom !== Viewports.getZoom(view.origin).value)
            Viewports.zoomTo(view.origin, zoom, Boxes.center(rvg.frame), view.origin)
        const pan = Viewports.getPan(view.origin)
        if (zoom === drawnZoom) {
            map.anchor.x = drawnAnchor.x + pan.x - drawnPan.x
            map.anchor.y = drawnAnchor.y + pan.y - drawnPan.y
        }
        if (zoom !== drawnZoom || Math.abs(pan.x - drawnPan.x) > margin || Math.abs(pan.y - drawnPan.y) > margin)
            draw(zoom, { x: pan.x, y: pan.y })
    })
}

The places of Europe as dots in a zoomable Web Mercator view. Scroll to zoom and drag to pan: each label appears from the zoom at which it overlaps no other, larger places first. Declutter.boxes computes these zooms once, with the population as priority.

How it works

Each label is a box in world coordinates, from its dot to the end of its text. Declutter.boxes returns, for every label, the smallest scale at which it is shown, with the population as priority:

const minScale = Declutter.boxes(boxes, places.map(p => p[3]), { padding, anchor: [0, 0.5] })
  • anchor: [0, 0.5]: the middle of the box's left side stays at the dot.

The computation runs once. A viewport pans and zooms; dots and labels keep their size, so they sit in a layer above its content. The viewport's zoom is Declutter's scale:

labels[i].visible.value = inView && zoom >= minScale[i]

Hidden labels stay in the DOM (visible). A pan only moves the layer.

Notes

Places: Natural Earth, "Populated Places (simple)", 1:10m, public domain (places.ts), all places between longitude -25 and 45 and latitude 34 and 72.

API

  • Declutter.boxes: the smallest scale at which each label is shown
  • canvas.viewports.box, Viewports.getZoom, Viewports.getPan, Viewports.zoomTo: panning and zooming

See also

  • declutter/declutter-01-timeline

API used

Also used (25)