Mapping: Points + Labels

Place markers on an image with scaled transform and hover labels.

Example 1: Markers + Tooltips

Code

let img;
const points = [
  { x: 0.2, y: 0.25, label: 'North' },
  { x: 0.55, y: 0.52, label: 'Center' },
  { x: 0.78, y: 0.74, label: 'South-East' }
];

function preload() {
  img = loadImage('../assets/images/map.jpg');
}

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(248);
  const fit = fitImage(img.width, img.height, width, height, 20);
  image(img, fit.dx, fit.dy, fit.dw, fit.dh);

  for (const p of points) {
    const cx = fit.dx + p.x * fit.dw;
    const cy = fit.dy + p.y * fit.dh;
    fill(255, 45, 140);
    noStroke();
    circle(cx, cy, 12);

    if (dist(mouseX, mouseY, cx, cy) < 12) {
      fill(20);
      rect(cx + 10, cy - 24, textWidth(p.label) + 16, 22, 4);
      fill(255);
      text(p.label, cx + 18, cy - 9);
    }
  }
}

function fitImage(iw, ih, cw, ch, pad) {
  const ratio = min((cw - pad * 2) / iw, (ch - pad * 2) / ih);
  const dw = iw * ratio;
  const dh = ih * ratio;
  return { dx: (cw - dw) / 2, dy: (ch - dh) / 2, dw, dh };
}

Try this: Add your own marker objects in image coordinates.

Open sketch in new tab

Example 2: Image Coordinate Crosshair

Code

let img;

function preload() {
  img = loadImage('../assets/images/map.jpg');
}

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(255);
  const fit = fitImage(img.width, img.height, width, height, 24);
  image(img, fit.dx, fit.dy, fit.dw, fit.dh);

  const u = constrain((mouseX - fit.dx) / fit.dw, 0, 1);
  const v = constrain((mouseY - fit.dy) / fit.dh, 0, 1);
  const ix = fit.dx + u * fit.dw;
  const iy = fit.dy + v * fit.dh;

  stroke(255, 45, 140);
  line(ix - 12, iy, ix + 12, iy);
  line(ix, iy - 12, ix, iy + 12);

  noStroke();
  fill(20);
  text('u: ' + u.toFixed(2) + ' v: ' + v.toFixed(2), 14, 20);
}

function fitImage(iw, ih, cw, ch, pad) {
  const ratio = min((cw - pad * 2) / iw, (ch - pad * 2) / ih);
  const dw = iw * ratio;
  const dh = ih * ratio;
  return { dx: (cw - dw) / 2, dy: (ch - dh) / 2, dw, dh };
}

Try this: Display rounded latitude/longitude style labels from u/v.

Open sketch in new tab

Resources