Selecting Objects in a WebGL Map

In my previous article, I covered building a vector map from scratch using WebGL. By the end we had a map that could pan, zoom, and render layers from a vector tile server. But what if we want to know more about what's actually on the map?

Most mapping libraries let you hover (or click) on a building, a park or a road, and get some information back about it. This is generally referred to as picking, and it's a bit trickier than it sounds when everything is drawn with WebGL.

In this article, I'll go over how picking works, and then walk through adding it to the map from the last article, so we can show a popup with the properties of whatever is under the mouse.

hovering a feature highlights it, and shows its properties in a popup.

hovering a feature highlights it, and shows its properties in a popup.

TL;DR - You can also skip straight to the final result.

The problem with a canvas

If the map was made up of regular DOM elements, this would be pretty simple. Each building would be its own element, and we could just add a mouseover listener to it.

With WebGL though, the entire map is a single <canvas> element. The browser can tell us where the mouse is on the canvas, but it has no idea what was drawn there. As far as it's concerned, the map is just a grid of pixels.

So we need some way of getting from a pixel on the screen, back to the feature that was drawn there.

How picking works

There are generally two ways to go about this.

The first is to do the math ourselves. We already have a matrix that converts a coordinate to a position on the screen, so we can invert it to get the coordinate under the mouse (similar to how we handled zooming in the last article). From there, we can loop through the features and check which ones contain that point.

This works, but it has a few downsides. We'd need to test the point against every feature in view (or build some kind of index to narrow them down), and there can easily be tens of thousands of them. We'd also need to work out which feature is on top when they overlap, which means keeping the picking code in sync with how the map is rendered.

The second option is to let the GPU do the work, using a technique called color picking. The idea is to render the map a second time, but instead of using the normal colors, each feature is drawn with its own unique color. Then all we need to do is look at the color of the pixel under the mouse, and we know which feature it is.

each feature is rendered in a unique color, which maps back to its id.

each feature is rendered in a unique color, which maps back to its id.

The nice thing about this approach is that the GPU has already done the hard part. Whatever color ends up at that pixel is whatever was drawn on top, regardless of how many features there are, or how complex the shapes are.

This is also how picking works in DeckGL. If you've ever set pickable: true on a layer (like the GeoJSON layer in a previous article), this is what's happening under the hood. There's also a great article at webglfundamentals.org that goes into more detail.

Encoding IDs as colors

The first thing we need is a way to turn an ID into a color, and back again.

A pixel is made up of four channels (red, green, blue and alpha), each stored as a single byte with a value from 0 to 255. If we spread an ID across the red, green and blue bytes, that gives us 2563 (about 16.7 million) possible IDs, which should be plenty for our purposes.

// encode a feature id as an RGBA color const idToColor = (id) => [ id & 0xff, // red (id >> 8) & 0xff, // green (id >> 16) & 0xff, // blue 255, // alpha ]; // decode an RGBA color back to a feature id const colorToId = ([r, g, b]) => ( r + (g << 8) + (b << 16) ); idToColor(5047); // [183, 19, 0, 255] colorToId([183, 19, 0, 255]); // 5047

We'll leave the alpha channel alone so the colors are always opaque, and reserve an ID of 0 to mean "nothing", since that's what an empty pixel will give us.

Assigning IDs to features

Next, every feature needs an ID. The features in a vector tile do come with their own id, but those can be much larger than the 16.7 million we have room for. So instead, we'll hand out our own IDs as the tiles are parsed, starting from 1.

There's one catch. In Part 3 of the last article, we combined the vertices for every feature in a layer into a single array, to cut down on the number of draw calls. That means by the time the data gets to WebGL, there's no concept of a feature anymore. It's all just triangles.

So to give each feature its own color, we'll build a second array with a color for every vertex. All of the vertices that belong to a feature get the same color.

const vertices = []; const pickColors = []; const features = {}; // id -> properties getFeatures(vectorTile.layers[layer]).forEach((feature) => { const geojson = feature.toGeoJSON(x, y, z); const featureVertices = geometryToVertices(geojson.geometry); append(vertices, featureVertices); // assign an id, and hold on to the properties for looking up later const id = getPickId(feature, layer, z); features[id] = { layer, properties: feature.properties }; // every vertex in the feature gets the same color const color = idToColor(id); for (let v = 0; v < featureVertices.length / 2; v++) { append(pickColors, color); } }); tileData.push({ layer, vertices: Float32Array.from(vertices), pickColors: Uint8Array.from(pickColors), features, });

We're also holding on to the properties of each feature here, which we'll need later for the popup.

One other thing to note is that larger features (like a park, or the East River) get split up across multiple tiles. If each piece got a new ID, they'd be treated as separate features. To get around that, getPickId keeps track of the IDs it's already handed out, and re-uses them when the same feature shows up in another tile.

The features also aren't always in the same order from one tile to the next. Up to now that hasn't mattered, since everything in a layer is the same color. But with picking, whatever gets drawn last is what gets picked, so we'll sort the features by their id to keep that consistent.

Rendering the IDs

Now that every vertex has a color, we need to get it into the shaders. We'll add an a_pickColor attribute to the vertex shader, which just passes the value along to the fragment shader as a varying. For now, the fragment shader will use it as the output color.

attribute vec2 a_position; attribute vec4 a_pickColor; uniform mat3 u_matrix; // 3 X 3 matrix varying vec4 v_pickColor; void main() { v_pickColor = a_pickColor; vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); }

Loading the colors into WebGL works the same way as the vertices, with a couple of differences. Each color is 4 unsigned bytes (rather than 2 floats), and we set normalize to true so the values get converted from 0 - 255 to the 0 - 1 range that the shader expects.

// create buffer for pick colors gl.bindBuffer(gl.ARRAY_BUFFER, pickColorBuffer); gl.bufferData(gl.ARRAY_BUFFER, pickColors, gl.STATIC_DRAW); // setup pick color attribute gl.enableVertexAttribArray(pickColorAttributeLocation); // each color is 4 bytes (RGBA), normalized from 0 - 255 to 0 - 1 const size = 4; const type = gl.UNSIGNED_BYTE; const normalize = true; const stride = 0; const offset = 0; gl.vertexAttribPointer(pickColorAttributeLocation, size, type, normalize, stride, offset);

Once the map is drawn, we can use gl.readPixels to grab the color of the pixel under the mouse, and convert it back to an ID. The one thing to watch out for is that WebGL puts the origin at the bottom-left, whereas mouse positions are relative to the top-left, so we need to flip the y value.

// webgl has the origin at the bottom-left, so flip the y const x = mouse.x; const y = canvas.height - mouse.y - 1; // read the color of the pixel under the mouse const pixel = new Uint8Array(4); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); const id = colorToId(pixel);

Here's the map rendered with the pick colors. As you move the mouse around, you can see the pixel that was read, and the ID it converts to, in the bottom-left corner.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 import { mat3, vec3 } from 'gl-matrix'; import tilebelt from '@mapbox/tilebelt'; import MercatorCoordinate from './mercator-coordinate'; import Stats from 'stats.js'; import { createShader, createProgram } from './webgl-utils'; import { colorToId } from './picking-map-utils'; import config from '../config'; ////////////////////// // constants ////////////////////// const TILE_SERVER_URL = `https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf?apiKey=${config('mapsApiKey')}`; const TILE_SIZE = 512; const MAX_TILE_ZOOM = 14; const MIN_ZOOM = 0; const MAX_ZOOM = 16; ////////////////////// // shaders ////////////////////// // vertex shader passes the pick color (the feature id) // along to the fragment shader const vertexShaderSource = ` attribute vec2 a_position; attribute vec4 a_pickColor; uniform mat3 u_matrix; // 3 X 3 matrix varying vec4 v_pickColor; void main() { v_pickColor = a_pickColor; vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); } `; // render each feature using its pick color const fragmentShaderSource =` precision mediump float; varying vec4 v_pickColor; void main() { gl_FragColor = v_pickColor; } `; ////////////////////// // map state ////////////////////// let loopRunning = true; let frame; // id of the next animation frame const camera = { x: 0, y: 0, zoom: 0, }; // initial transformation (Dumbo, Brooklyn) [camera.x, camera.y] = MercatorCoordinate.fromLngLat([-73.9876, 40.7025]); camera.zoom = 15; // DOM elements let canvas; let readout; let statsWidget; const LAYERS = { water: [180, 240, 250, 255], landcover: [202, 246, 193, 255], park: [202, 255, 193, 255], building: [185, 175, 139, 191], }; const TILE_BUFFER = 1; // 1 tile in each direction let tiles = {}; // tile -> layers let tilesInView = []; let tileWorker; ////////////////////// // picking state ////////////////////// let mouse = null; // mouse position on the canvas (in pixels) let hoveredId = 0; // id of the feature under the mouse (0 is nothing) function updateTiles() { const bbox = getBounds(); const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM); const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z); const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z); // tiles visible in viewport tilesInView = []; const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]]; const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]]; for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) { tilesInView.push([x, y, z]); } } // load additional tiles outside of viewport let bufferedTiles = []; for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) { for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) { bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction // load parent tiles 2 levels up bufferedTiles.push(tilebelt.getParent([bufX, bufY, z])); bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z]))); } } // remove dupes from in view let tilesToLoad = [ ...new Set([ ...tilesInView.map(t => t.join('/')), ...bufferedTiles.map(t => t.join('/')) ]) ]; // make sure tiles are in range tilesToLoad = tilesToLoad.filter((tile) => { const [x, y, z] = tile.split('/').map(Number); const N = Math.pow(2, z); const validX = x >= 0 && x < N; const validY = y >= 0 && y < N; const validZ = z >= 0 && z <= MAX_TILE_ZOOM; return validX && validY && validZ; }); tilesToLoad.forEach((tile) => { if (tiles[tile]) { return; // already loaded, no need to fetch } tiles[tile] = []; // temp hold for request // load every tile in the worker, so all the feature ids come from the same place tileWorker.postMessage({ tile, layers: LAYERS, url: TILE_SERVER_URL }); }); } let matrix; function updateMatrix() { const cameraMat = mat3.create(); // translate mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]); // scale const zoomScale = 1 / Math.pow(2, camera.zoom); const widthScale = TILE_SIZE / canvas.width; const heightScale = TILE_SIZE / canvas.height; mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]); // update matrix matrix = mat3.multiply( [], mat3.create(), // identity matrix mat3.invert([], cameraMat) // invert camera position ); } // show the pixel that was read, and the id it decodes to function updateReadout(pixel) { readout.textContent = [ `pixel: ${pixel ? `[${pixel.join(', ')}]` : '-'}`, `id: ${pixel ? hoveredId : '-'}`, ].join('\n'); } ////////////////////// // helpers ////////////////////// function getClipSpacePosition(e) { // handle mouse and touch events const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left; const cssY = y - rect.top; // get normalized 0 to 1 position across and down canvas const normalizedX = cssX / canvas.clientWidth; const normalizedY = cssY / canvas.clientHeight; // convert to clip space const clipX = normalizedX * 2 - 1; const clipY = normalizedY * -2 + 1; return [clipX, clipY]; } // get the pixel on the canvas for a mouse or touch event function getCanvasPosition(e) { const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position (minus the border) const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left - canvas.clientLeft; const cssY = y - rect.top - canvas.clientTop; // convert to pixels, in case the canvas is being scaled const pixelX = Math.floor(cssX * canvas.width / canvas.clientWidth); const pixelY = Math.floor(cssY * canvas.height / canvas.clientHeight); return { x: Math.max(0, Math.min(pixelX, canvas.width - 1)), y: Math.max(0, Math.min(pixelY, canvas.height - 1)), }; } // get bbox coordinates for viewport function getBounds() { const zoomScale = Math.pow(2, camera.zoom); // undo clip-space const px = (1 + camera.x) / 2; const py = (1 - camera.y) / 2; // get world coord in px const wx = px * TILE_SIZE; const wy = py * TILE_SIZE; // get zoom px const zx = wx * zoomScale; const zy = wy * zoomScale; // get bottom-left and top-right pixels let x1 = zx - (canvas.width / 2); let y1 = zy + (canvas.height / 2); let x2 = zx + (canvas.width / 2); let y2 = zy - (canvas.height / 2); // convert to world coords x1 = x1 / zoomScale / TILE_SIZE; y1 = y1 / zoomScale / TILE_SIZE; x2 = x2 / zoomScale / TILE_SIZE; y2 = y2 / zoomScale / TILE_SIZE; // get LngLat bounding box const bbox = [ Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180), Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05), Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180), Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05), ]; return bbox; } function atLimits() { const bbox = getBounds(); return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05; } ////////////////////// // main program ////////////////////// let hammer; let handlePan; let handleZoom; let handleHover; let handleLeave; let timestamp; let slowCount; const run = (canvasId, abort) => { // setup loop state loopRunning = true; timestamp = 0; slowCount = 0; // create stats object for widget const stats = new Stats(); // get GL context from canvas // (no antialiasing, otherwise colors get blended along the edges of a feature) canvas = document.getElementById(canvasId); const gl = canvas.getContext("webgl", { antialias: false }); // create readout for the picked pixel readout = document.createElement('div'); readout.className = 'webgl-map-readout'; canvas.parentElement.appendChild(readout); // setup tile worker // (only once, since the worker is keeping track of the feature ids) if (!tileWorker) { tileWorker = new Worker(new URL('./picking-tile-worker.js', import.meta.url)); tileWorker.onmessage = (event) => { const { tile, tileData } = event.data; tiles[tile] = tileData; }; tileWorker.onerror = (error) => { console.error('Uncaught worker error.', error); }; } // setup initial state updateMatrix(); updateTiles(); // setup viewport gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // compile shaders const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource); const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource); // init gl program const program = createProgram(gl, vertexShader, fragmentShader); gl.useProgram(program); gl.clearColor(0, 0, 0, 0); // lookup attributes and uniforms const positionAttributeLocation = gl.getAttribLocation(program, "a_position"); const pickColorAttributeLocation = gl.getAttribLocation(program, "a_pickColor"); const matrixLocation = gl.getUniformLocation(program, "u_matrix"); // create buffers const positionBuffer = gl.createBuffer(); const pickColorBuffer = gl.createBuffer(); // render the tiles in view const drawTiles = () => { tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { layer, vertices, pickColors } = tileLayer; if (LAYERS[layer]) { // create buffer for vertices gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); // setup position attribute gl.enableVertexAttribArray(positionAttributeLocation); // tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER) let size = 2; let type = gl.FLOAT; let normalize = false; const stride = 0; let offset = 0; gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset); // create buffer for pick colors gl.bindBuffer(gl.ARRAY_BUFFER, pickColorBuffer); gl.bufferData(gl.ARRAY_BUFFER, pickColors, gl.STATIC_DRAW); // setup pick color attribute gl.enableVertexAttribArray(pickColorAttributeLocation); // each color is 4 bytes (RGBA), normalized from 0 - 255 to 0 - 1 size = 4; type = gl.UNSIGNED_BYTE; normalize = true; gl.vertexAttribPointer(pickColorAttributeLocation, size, type, normalize, stride, offset); // draw const primitiveType = gl.TRIANGLES; offset = 0; const count = vertices.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // read the pixel under the mouse (straight from the canvas) const readPixel = () => { // webgl has the origin at the bottom-left, so flip the y const x = mouse.x; const y = canvas.height - mouse.y - 1; const pixel = new Uint8Array(4); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); return pixel; }; const draw = () => { stats.begin(); // set matrix as uniform gl.uniformMatrix3fv(matrixLocation, false, matrix); // render tiles drawTiles(); // find the id of the feature under the mouse const pixel = mouse ? readPixel() : null; hoveredId = pixel ? colorToId(pixel) : 0; updateReadout(pixel); // kill loop if gets too slow // 10 frames under 10 FPS const now = performance.now(); const fps = 1 / ((now - timestamp) / 1000); if (fps < 10) { slowCount++; if (slowCount > 10) { console.warn(`Too slow. Killing loop for ${canvasId}.`); stop(); if (abort) { abort(); } } } timestamp = now; // end of loop stats.end(); if (loopRunning) { frame = window.requestAnimationFrame(draw); } } frame = window.requestAnimationFrame(draw); // start loop //////////////////////// // interaction handlers //////////////////////// // handle touch events const Hammer = require('hammerjs'); hammer = new Hammer(canvas); hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL }); hammer.get('pinch').set({ enable: true }); // keep track of the mouse position for picking handleHover = (event) => { mouse = getCanvasPosition(event); }; canvas.addEventListener('mousemove', handleHover); hammer.on('tap', handleHover); // no hover on mobile, so use tap handleLeave = () => { mouse = null; }; canvas.addEventListener('mouseleave', handleLeave); // handle pan events let startX; let startY; // handle drag changes while mouse is still down const handleMove = (moveEvent) => { const [x, y] = getClipSpacePosition(moveEvent); // compute the previous position in world space const [preX, preY] = vec3.transformMat3( [], [startX, startY, 0], mat3.invert([], matrix) ); // compute the new position in world space const [postX, postY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // move that amount, because how much the position changes depends on the zoom level const deltaX = preX - postX; const deltaY = preY - postY; if (isNaN(deltaX) || isNaN(deltaY)) { return; // abort } // only update within world limits camera.x += deltaX; camera.y += deltaY; // update matrix with new camera updateMatrix(); // prevent further pan if at limits if (atLimits()) { camera.x -= deltaX; camera.y -= deltaY; updateMatrix(); return; // abort } // save current pos for next movement startX = x; startY = y; updateMatrix(); updateTiles(); } handlePan = (startEvent) => { // get position of initial drag [startX, startY] = getClipSpacePosition(startEvent); canvas.style.cursor = 'grabbing'; window.addEventListener('mousemove', handleMove); hammer.on('pan', handleMove); // clear on release const clear = (event) => { canvas.style.cursor = 'grab'; window.removeEventListener('mousemove', handleMove); window.removeEventListener('mouseup', clear); hammer.off('pan', handleMove); hammer.off('panend', clear); }; window.addEventListener('mouseup', clear); hammer.on('panend', clear); } canvas.addEventListener('mousedown', handlePan); hammer.on('panstart', handlePan); // handle zoom events handleZoom = (wheelEvent) => { wheelEvent.preventDefault(); const [x, y] = getClipSpacePosition(wheelEvent); // get position before zooming const [preZoomX, preZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // update current zoom state const prevZoom = camera.zoom; const zoomDelta = -wheelEvent.deltaY * (1 / 500); camera.zoom += zoomDelta; camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM)); updateMatrix(); // prevent further zoom if at limits if (atLimits()) { camera.zoom = prevZoom updateMatrix(); return; } // get new position after zooming const [postZoomX, postZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // camera needs to be translated the difference of before and after camera.x += preZoomX - postZoomX; camera.y += preZoomY - postZoomY; updateMatrix(); updateTiles(); } canvas.addEventListener('wheel', handleZoom); hammer.on('pinch', handleZoom); // setup stats widget stats.showPanel(0); // frame rate statsWidget = stats.dom; statsWidget.style.position = 'absolute'; statsWidget.style.zIndex = '0'; canvas.parentElement.appendChild(statsWidget); }; export const stop = () => { loopRunning = false; window.cancelAnimationFrame(frame); if (!canvas) { return; // not running, nothing to clean up } // clear event handlers canvas.removeEventListener('wheel', handleZoom); canvas.removeEventListener('mousedown', handlePan); canvas.removeEventListener('mousemove', handleHover); canvas.removeEventListener('mouseleave', handleLeave); hammer.destroy(); // clear DOM elements statsWidget.remove(); readout.remove(); canvas = null; mouse = null; hoveredId = 0; }; export default run;
Alert iconNote: antialiasing is turned off for this map. Otherwise the pixels along the edge of a feature get blended with whatever is next to them, and we'd end up reading a color (and an ID) that doesn't exist.

The colors aren't much to look at, but they don't need to be. Since the IDs are handed out in order, the first 255 are all shades of red. After that they start to creep into the green channel, which is where the oranges and greens come from.

Rendering to a framebuffer

This isn't something we'd want to show on the actual map though. What we really want is to render the pick colors somewhere off-screen, and keep the normal colors on the canvas.

Fortunately, WebGL lets us do exactly that with a framebuffer. Instead of drawing to the canvas, we can create a framebuffer backed by a texture (basically an image that lives on the GPU) and draw into that instead.

// create a texture to render the pick colors into (same size as the canvas) const pickTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, pickTexture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); // create a framebuffer, and attach the texture to it const pickFramebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, pickTexture, 0);

Once that's set up, we choose where to draw by binding the framebuffer first. Binding null switches back to the canvas.

So for every frame, we'll now render the map twice. Once to the framebuffer with the pick colors (where we read the pixel under the mouse), and then again to the canvas with the normal colors.

// render the pick colors to the framebuffer gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer); gl.clear(gl.COLOR_BUFFER_BIT); drawTiles(true); // read the color of the pixel under the mouse const pixel = new Uint8Array(4); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); hoveredId = colorToId(pixel); // render the normal colors to the canvas gl.bindFramebuffer(gl.FRAMEBUFFER, null); drawTiles(false);

Since both passes are drawing the same vertices, we can use the same shaders for both. We just need a u_picking uniform to tell the fragment shader which color to output.

uniform bool u_picking; uniform vec4 u_color; varying vec4 v_pickColor; void main() { if (u_picking) { gl_FragColor = v_pickColor; } else { gl_FragColor = u_color; } }

There are a couple of other benefits to rendering off-screen. The framebuffer isn't antialiased, and anything that isn't a feature (like the tile boundaries) can just be left out. So the color we read back is always exactly what we put in.

Highlighting the feature

Now that we know which feature is under the mouse, it'd be nice to show that on the map. Since the vertex shader already has the pick color for every vertex, we can pass in the color of the hovered feature as a uniform, and check if they match. If they do, the fragment shader uses a highlight color instead of the layer color.

attribute vec2 a_position; attribute vec4 a_pickColor; uniform mat3 u_matrix; // 3 X 3 matrix uniform vec4 u_hoveredColor; // pick color of the feature under the mouse varying vec4 v_pickColor; varying float v_hovered; void main() { v_pickColor = a_pickColor; v_hovered = distance(a_pickColor, u_hoveredColor) < 0.001 ? 1.0 : 0.0; vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 import { mat3, vec3 } from 'gl-matrix'; import tilebelt from '@mapbox/tilebelt'; import MercatorCoordinate from './mercator-coordinate'; import Stats from 'stats.js'; import { createShader, createProgram } from './webgl-utils'; import { geometryToVertices } from './map-utils'; import { idToColor, colorToId } from './picking-map-utils'; import config from '../config'; ////////////////////// // constants ////////////////////// const TILE_SERVER_URL = `https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf?apiKey=${config('mapsApiKey')}`; const TILE_SIZE = 512; const MAX_TILE_ZOOM = 14; const MIN_ZOOM = 0; const MAX_ZOOM = 16; const HIGHLIGHT_COLOR = [255, 211, 67, 255]; ////////////////////// // shaders ////////////////////// // vertex shader passes along the pick color (the feature id), // and checks if the vertex is part of the hovered feature const vertexShaderSource = ` attribute vec2 a_position; attribute vec4 a_pickColor; uniform mat3 u_matrix; // 3 X 3 matrix uniform vec4 u_hoveredColor; // pick color of the feature under the mouse varying vec4 v_pickColor; varying float v_hovered; void main() { v_pickColor = a_pickColor; v_hovered = distance(a_pickColor, u_hoveredColor) < 0.001 ? 1.0 : 0.0; vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); } `; // fragment shader outputs the pick color when rendering to the picking buffer, // otherwise the layer color (or highlight color if hovered) const fragmentShaderSource =` precision mediump float; uniform bool u_picking; uniform vec4 u_color; uniform vec4 u_highlightColor; varying vec4 v_pickColor; varying float v_hovered; void main() { if (u_picking) { gl_FragColor = v_pickColor; } else if (v_hovered > 0.5) { gl_FragColor = u_highlightColor; } else { gl_FragColor = u_color; } } `; ////////////////////// // map state ////////////////////// let loopRunning = true; let frame; // id of the next animation frame const camera = { x: 0, y: 0, zoom: 0, }; // initial transformation (Dumbo, Brooklyn) [camera.x, camera.y] = MercatorCoordinate.fromLngLat([-73.9876, 40.7025]); camera.zoom = 15; // DOM elements let canvas; let overlay; let readout; let statsWidget; const LAYERS = { water: [180, 240, 250, 255], landcover: [202, 246, 193, 255], park: [202, 255, 193, 255], building: [185, 175, 139, 191], }; const TILE_BUFFER = 1; // 1 tile in each direction let tiles = {}; // tile -> layers let tilesInView = []; let tileWorker; ////////////////////// // picking state ////////////////////// let gl; let pickTexture; let pickFramebuffer; let mouse = null; // mouse position on the canvas (in pixels) let hoveredId = 0; // id of the feature under the mouse (0 is nothing) function updateTiles() { const bbox = getBounds(); const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM); const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z); const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z); // tiles visible in viewport tilesInView = []; const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]]; const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]]; for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) { tilesInView.push([x, y, z]); } } // load additional tiles outside of viewport let bufferedTiles = []; for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) { for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) { bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction // load parent tiles 2 levels up bufferedTiles.push(tilebelt.getParent([bufX, bufY, z])); bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z]))); } } // remove dupes from in view let tilesToLoad = [ ...new Set([ ...tilesInView.map(t => t.join('/')), ...bufferedTiles.map(t => t.join('/')) ]) ]; // make sure tiles are in range tilesToLoad = tilesToLoad.filter((tile) => { const [x, y, z] = tile.split('/').map(Number); const N = Math.pow(2, z); const validX = x >= 0 && x < N; const validY = y >= 0 && y < N; const validZ = z >= 0 && z <= MAX_TILE_ZOOM; return validX && validY && validZ; }); tilesToLoad.forEach((tile) => { if (tiles[tile]) { return; // already loaded, no need to fetch } tiles[tile] = []; // temp hold for request // load every tile in the worker, so all the feature ids come from the same place tileWorker.postMessage({ tile, layers: LAYERS, url: TILE_SERVER_URL }); }); } let matrix; function updateMatrix() { const cameraMat = mat3.create(); // translate mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]); // scale const zoomScale = 1 / Math.pow(2, camera.zoom); const widthScale = TILE_SIZE / canvas.width; const heightScale = TILE_SIZE / canvas.height; mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]); // update matrix matrix = mat3.multiply( [], mat3.create(), // identity matrix mat3.invert([], cameraMat) // invert camera position ); } // show the pixel that was read, and the id it decodes to function updateReadout(pixel) { readout.textContent = [ `pixel: ${pixel ? `[${pixel.join(', ')}]` : '-'}`, `id: ${pixel ? hoveredId : '-'}`, ].join('\n'); } ////////////////////// // helpers ////////////////////// function getClipSpacePosition(e) { // handle mouse and touch events const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left; const cssY = y - rect.top; // get normalized 0 to 1 position across and down canvas const normalizedX = cssX / canvas.clientWidth; const normalizedY = cssY / canvas.clientHeight; // convert to clip space const clipX = normalizedX * 2 - 1; const clipY = normalizedY * -2 + 1; return [clipX, clipY]; } // get the pixel on the canvas for a mouse or touch event function getCanvasPosition(e) { const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position (minus the border) const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left - canvas.clientLeft; const cssY = y - rect.top - canvas.clientTop; // convert to pixels, in case the canvas is being scaled const pixelX = Math.floor(cssX * canvas.width / canvas.clientWidth); const pixelY = Math.floor(cssY * canvas.height / canvas.clientHeight); return { x: Math.max(0, Math.min(pixelX, canvas.width - 1)), y: Math.max(0, Math.min(pixelY, canvas.height - 1)), }; } // get bbox coordinates for viewport function getBounds() { const zoomScale = Math.pow(2, camera.zoom); // undo clip-space const px = (1 + camera.x) / 2; const py = (1 - camera.y) / 2; // get world coord in px const wx = px * TILE_SIZE; const wy = py * TILE_SIZE; // get zoom px const zx = wx * zoomScale; const zy = wy * zoomScale; // get bottom-left and top-right pixels let x1 = zx - (canvas.width / 2); let y1 = zy + (canvas.height / 2); let x2 = zx + (canvas.width / 2); let y2 = zy - (canvas.height / 2); // convert to world coords x1 = x1 / zoomScale / TILE_SIZE; y1 = y1 / zoomScale / TILE_SIZE; x2 = x2 / zoomScale / TILE_SIZE; y2 = y2 / zoomScale / TILE_SIZE; // get LngLat bounding box const bbox = [ Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180), Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05), Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180), Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05), ]; return bbox; } function atLimits() { const bbox = getBounds(); return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05; } ////////////////////// // main program ////////////////////// let hammer; let handlePan; let handleZoom; let handleHover; let handleLeave; let timestamp; let slowCount; const run = (canvasId, abort) => { // setup loop state loopRunning = true; timestamp = 0; slowCount = 0; // create stats object for widget const stats = new Stats(); // get GL context from canvas canvas = document.getElementById(canvasId); gl = canvas.getContext("webgl"); // get overlay overlay = document.getElementById(`${canvasId}-overlay`); // create readout for the picked pixel readout = document.createElement('div'); readout.className = 'webgl-map-readout'; canvas.parentElement.appendChild(readout); // setup tile worker // (only once, since the worker is keeping track of the feature ids) if (!tileWorker) { tileWorker = new Worker(new URL('./picking-tile-worker.js', import.meta.url)); tileWorker.onmessage = (event) => { const { tile, tileData } = event.data; tiles[tile] = tileData; }; tileWorker.onerror = (error) => { console.error('Uncaught worker error.', error); }; } // setup initial state updateMatrix(); updateTiles(); // setup viewport gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // compile shaders const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource); const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource); // init gl program const program = createProgram(gl, vertexShader, fragmentShader); gl.useProgram(program); gl.clearColor(0, 0, 0, 0); // lookup attributes and uniforms const positionAttributeLocation = gl.getAttribLocation(program, "a_position"); const pickColorAttributeLocation = gl.getAttribLocation(program, "a_pickColor"); const matrixLocation = gl.getUniformLocation(program, "u_matrix"); const colorLocation = gl.getUniformLocation(program, "u_color"); const pickingLocation = gl.getUniformLocation(program, "u_picking"); const hoveredColorLocation = gl.getUniformLocation(program, "u_hoveredColor"); const highlightColorLocation = gl.getUniformLocation(program, "u_highlightColor"); // highlight color is always the same gl.uniform4fv(highlightColorLocation, HIGHLIGHT_COLOR.map(n => n / 255)); // create buffers const positionBuffer = gl.createBuffer(); const pickColorBuffer = gl.createBuffer(); // create a texture to render the pick colors into (same size as the canvas) pickTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, pickTexture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); // create a framebuffer, and attach the texture to it pickFramebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, pickTexture, 0); gl.bindFramebuffer(gl.FRAMEBUFFER, null); // back to the canvas // render the tiles in view, to either the canvas or the picking buffer const drawTiles = (picking) => { gl.uniform1i(pickingLocation, picking ? 1 : 0); tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { layer, vertices, pickColors } = tileLayer; if (LAYERS[layer]) { const color = LAYERS[layer].map(n => n / 255); // set color uniform for layer gl.uniform4fv(colorLocation, color); // create buffer for vertices gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); // setup position attribute gl.enableVertexAttribArray(positionAttributeLocation); // tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER) let size = 2; let type = gl.FLOAT; let normalize = false; const stride = 0; let offset = 0; gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset); // create buffer for pick colors gl.bindBuffer(gl.ARRAY_BUFFER, pickColorBuffer); gl.bufferData(gl.ARRAY_BUFFER, pickColors, gl.STATIC_DRAW); // setup pick color attribute gl.enableVertexAttribArray(pickColorAttributeLocation); // each color is 4 bytes (RGBA), normalized from 0 - 255 to 0 - 1 size = 4; type = gl.UNSIGNED_BYTE; normalize = true; gl.vertexAttribPointer(pickColorAttributeLocation, size, type, normalize, stride, offset); // draw const primitiveType = gl.TRIANGLES; offset = 0; const count = vertices.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // read the pixel under the mouse from the picking buffer const pick = () => { // render to the picking buffer instead of the canvas gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer); gl.clear(gl.COLOR_BUFFER_BIT); drawTiles(true); // webgl has the origin at the bottom-left, so flip the y const x = mouse.x; const y = canvas.height - mouse.y - 1; // read the color of the pixel under the mouse const pixel = new Uint8Array(4); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); // go back to rendering to the canvas gl.bindFramebuffer(gl.FRAMEBUFFER, null); return pixel; }; const draw = () => { stats.begin(); // set matrix as uniform gl.uniformMatrix3fv(matrixLocation, false, matrix); // find the id of the feature under the mouse const pixel = mouse ? pick() : null; hoveredId = pixel ? colorToId(pixel) : 0; updateReadout(pixel); // tell the shader which feature to highlight gl.uniform4fv(hoveredColorLocation, idToColor(hoveredId).map(n => n / 255)); // render tiles drawTiles(false); overlay.replaceChildren(); // clear labels to redraw // tile boundaries aren't features, so they don't have a pick color gl.disableVertexAttribArray(pickColorAttributeLocation); gl.vertexAttrib4f(pickColorAttributeLocation, 0, 0, 0, 0); // render boundaries and label for tiles in view tilesInView.forEach((tile) => { gl.uniform4fv(colorLocation, [1, 0, 0, 1]); const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile)); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW); // setup position attribute gl.enableVertexAttribArray(positionAttributeLocation); // tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER) const size = 2; const type = gl.FLOAT; const normalize = false; const stride = 0; let offset = 0; gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset); // draw const primitiveType = gl.LINES; offset = 0; const count = tileVertices.length / 2; gl.drawArrays(primitiveType, offset, count); // draw tile labels const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates; const topLeft = tileCoordinates[0][0]; const [x, y] = MercatorCoordinate.fromLngLat(topLeft); const [clipX, clipY] = vec3.transformMat3( [], [x, y, 1], matrix, ); const wx = ((1 + clipX) / 2) * canvas.width; const wy = ((1 - clipY) / 2) * canvas.height; const div = document.createElement("div"); div.className = "tile-label"; div.style.left = (wx + 8) + "px"; div.style.top = (wy + 8) + "px"; div.style.position = 'absolute'; div.style.zIndex = 1000; div.style.pointerEvents = 'none'; // dont block the mouse from the canvas div.appendChild(document.createTextNode(tile.join('/'))); overlay.appendChild(div); }); // kill loop if gets too slow // 10 frames under 10 FPS const now = performance.now(); const fps = 1 / ((now - timestamp) / 1000); if (fps < 10) { slowCount++; if (slowCount > 10) { console.warn(`Too slow. Killing loop for ${canvasId}.`); stop(); if (abort) { abort(); } } } timestamp = now; // end of loop stats.end(); if (loopRunning) { frame = window.requestAnimationFrame(draw); } } frame = window.requestAnimationFrame(draw); // start loop //////////////////////// // interaction handlers //////////////////////// // handle touch events const Hammer = require('hammerjs'); hammer = new Hammer(canvas); hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL }); hammer.get('pinch').set({ enable: true }); // keep track of the mouse position for picking handleHover = (event) => { mouse = getCanvasPosition(event); }; canvas.addEventListener('mousemove', handleHover); hammer.on('tap', handleHover); // no hover on mobile, so use tap handleLeave = () => { mouse = null; }; canvas.addEventListener('mouseleave', handleLeave); // handle pan events let startX; let startY; // handle drag changes while mouse is still down const handleMove = (moveEvent) => { const [x, y] = getClipSpacePosition(moveEvent); // compute the previous position in world space const [preX, preY] = vec3.transformMat3( [], [startX, startY, 0], mat3.invert([], matrix) ); // compute the new position in world space const [postX, postY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // move that amount, because how much the position changes depends on the zoom level const deltaX = preX - postX; const deltaY = preY - postY; if (isNaN(deltaX) || isNaN(deltaY)) { return; // abort } // only update within world limits camera.x += deltaX; camera.y += deltaY; // update matrix with new camera updateMatrix(); // prevent further pan if at limits if (atLimits()) { camera.x -= deltaX; camera.y -= deltaY; updateMatrix(); return; // abort } // save current pos for next movement startX = x; startY = y; updateMatrix(); updateTiles(); } handlePan = (startEvent) => { // get position of initial drag [startX, startY] = getClipSpacePosition(startEvent); canvas.style.cursor = 'grabbing'; window.addEventListener('mousemove', handleMove); hammer.on('pan', handleMove); // clear on release const clear = (event) => { canvas.style.cursor = 'grab'; window.removeEventListener('mousemove', handleMove); window.removeEventListener('mouseup', clear); hammer.off('pan', handleMove); hammer.off('panend', clear); }; window.addEventListener('mouseup', clear); hammer.on('panend', clear); } canvas.addEventListener('mousedown', handlePan); hammer.on('panstart', handlePan); // handle zoom events handleZoom = (wheelEvent) => { wheelEvent.preventDefault(); const [x, y] = getClipSpacePosition(wheelEvent); // get position before zooming const [preZoomX, preZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // update current zoom state const prevZoom = camera.zoom; const zoomDelta = -wheelEvent.deltaY * (1 / 500); camera.zoom += zoomDelta; camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM)); updateMatrix(); // prevent further zoom if at limits if (atLimits()) { camera.zoom = prevZoom updateMatrix(); return; } // get new position after zooming const [postZoomX, postZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // camera needs to be translated the difference of before and after camera.x += preZoomX - postZoomX; camera.y += preZoomY - postZoomY; updateMatrix(); updateTiles(); } canvas.addEventListener('wheel', handleZoom); hammer.on('pinch', handleZoom); // setup stats widget stats.showPanel(0); // frame rate statsWidget = stats.dom; statsWidget.style.position = 'absolute'; statsWidget.style.zIndex = '0'; canvas.parentElement.appendChild(statsWidget); }; export const stop = () => { loopRunning = false; window.cancelAnimationFrame(frame); if (!canvas) { return; // not running, nothing to clean up } // clear event handlers canvas.removeEventListener('wheel', handleZoom); canvas.removeEventListener('mousedown', handlePan); canvas.removeEventListener('mousemove', handleHover); canvas.removeEventListener('mouseleave', handleLeave); hammer.destroy(); // clear DOM elements overlay.replaceChildren(); statsWidget.remove(); readout.remove(); // clear picking buffer gl.deleteFramebuffer(pickFramebuffer); gl.deleteTexture(pickTexture); canvas = null; mouse = null; hoveredId = 0; }; export default run;

As you move the mouse around, the feature underneath it should turn yellow. This also works for features that cross a tile boundary (the red lines), since both pieces share the same ID.

Only picking when we need to

At this point picking is working, but we're doing a lot of extra work to get there. We're rendering every tile twice on every frame, even if nothing has changed since the last one.

On top of that, gl.readPixels is a blocking call, meaning we have to wait for the GPU to finish rendering before we get the pixel back. So the less often we call it, the better.

The simplest fix is to only pick when something has actually changed: the mouse moved, the map moved, or a new tile finished loading. We can keep track of that with a needsPick flag, and skip the picking pass if it isn't set. We can also skip it while the map is being dragged.

// only pick when something has changed if (needsPick) { hoveredId = (mouse && !dragging) ? pick() : 0; needsPick = false; }

So if the mouse is sitting still (or isn't over the map at all), we're back to rendering the map once per frame.

We could also limit the picking pass to the single pixel we care about (using a scissor test), but in my testing it didn't make a noticeable difference. Most of the time seems to go into loading the vertices into the GPU, rather than filling in the pixels.

Showing a popup

The last piece is to actually do something with the feature we've picked. Earlier, we saved the properties for each feature when the tile was parsed. When a tile comes back from the worker, we can add those to a lookup keyed by ID.

tileWorker.onmessage = (event) => { const { tile, tileData } = event.data; tiles[tile] = tileData; // add features from the tile to the lookup (tileData || []).forEach((tileLayer) => { Object.assign(features, tileLayer.features); }); needsPick = true; // tile loaded, so there could be something new under the mouse };

The popup itself is just a regular DOM element positioned on top of the canvas. Whenever the hovered feature changes, we look up its properties, list them out in the popup, and move it next to the mouse.

// show the properties of the hovered feature in a popup function updatePopup() { const feature = features[hoveredId]; if (!feature) { popup.style.display = 'none'; popupId = 0; return; } // only rebuild the content when the feature changes if (popupId !== hoveredId) { popupId = hoveredId; const title = document.createElement('div'); title.className = 'popup-title'; title.textContent = feature.layer; popup.replaceChildren(title); Object.keys(feature.properties).forEach((key) => { const row = document.createElement('div'); const label = document.createElement('span'); label.className = 'popup-key'; label.textContent = `${key}: `; row.append(label, String(feature.properties[key])); popup.appendChild(row); }); } // position next to the mouse, but keep it inside of the map popup.style.display = 'block'; const left = Math.min(mouse.x + 12, canvas.width - popup.offsetWidth); const top = Math.min(mouse.y + 12, canvas.height - popup.offsetHeight); popup.style.left = `${left}px`; popup.style.top = `${top}px`; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 import { mat3, vec3 } from 'gl-matrix'; import tilebelt from '@mapbox/tilebelt'; import MercatorCoordinate from './mercator-coordinate'; import Stats from 'stats.js'; import { createShader, createProgram } from './webgl-utils'; import { geometryToVertices } from './map-utils'; import { idToColor, colorToId } from './picking-map-utils'; import config from '../config'; ////////////////////// // constants ////////////////////// const TILE_SERVER_URL = `https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf?apiKey=${config('mapsApiKey')}`; const TILE_SIZE = 512; const MAX_TILE_ZOOM = 14; const MIN_ZOOM = 0; const MAX_ZOOM = 16; const HIGHLIGHT_COLOR = [255, 211, 67, 255]; ////////////////////// // shaders ////////////////////// // vertex shader passes along the pick color (the feature id), // and checks if the vertex is part of the hovered feature const vertexShaderSource = ` attribute vec2 a_position; attribute vec4 a_pickColor; uniform mat3 u_matrix; // 3 X 3 matrix uniform vec4 u_hoveredColor; // pick color of the feature under the mouse varying vec4 v_pickColor; varying float v_hovered; void main() { v_pickColor = a_pickColor; v_hovered = distance(a_pickColor, u_hoveredColor) < 0.001 ? 1.0 : 0.0; vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); } `; // fragment shader outputs the pick color when rendering to the picking buffer, // otherwise the layer color (or highlight color if hovered) const fragmentShaderSource =` precision mediump float; uniform bool u_picking; uniform vec4 u_color; uniform vec4 u_highlightColor; varying vec4 v_pickColor; varying float v_hovered; void main() { if (u_picking) { gl_FragColor = v_pickColor; } else if (v_hovered > 0.5) { gl_FragColor = u_highlightColor; } else { gl_FragColor = u_color; } } `; ////////////////////// // map state ////////////////////// let loopRunning = true; let frame; // id of the next animation frame const camera = { x: 0, y: 0, zoom: 0, }; // initial transformation (Dumbo, Brooklyn) [camera.x, camera.y] = MercatorCoordinate.fromLngLat([-73.9876, 40.7025]); camera.zoom = 15; // DOM elements let canvas; let overlay; let popup; let statsWidget; const LAYERS = { water: [180, 240, 250, 255], landcover: [202, 246, 193, 255], park: [202, 255, 193, 255], building: [185, 175, 139, 191], }; const TILE_BUFFER = 1; // 1 tile in each direction let tiles = {}; // tile -> layers let features = {}; // id -> layer & properties let tilesInView = []; let tileWorker; ////////////////////// // picking state ////////////////////// let gl; let pickTexture; let pickFramebuffer; let mouse = null; // mouse position on the canvas (in pixels) let dragging = false; let needsPick = false; let hoveredId = 0; // id of the feature under the mouse (0 is nothing) let popupId = 0; // id of the feature shown in the popup function updateTiles() { const bbox = getBounds(); const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM); const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z); const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z); // tiles visible in viewport tilesInView = []; const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]]; const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]]; for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) { tilesInView.push([x, y, z]); } } // load additional tiles outside of viewport let bufferedTiles = []; for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) { for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) { bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction // load parent tiles 2 levels up bufferedTiles.push(tilebelt.getParent([bufX, bufY, z])); bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z]))); } } // remove dupes from in view let tilesToLoad = [ ...new Set([ ...tilesInView.map(t => t.join('/')), ...bufferedTiles.map(t => t.join('/')) ]) ]; // make sure tiles are in range tilesToLoad = tilesToLoad.filter((tile) => { const [x, y, z] = tile.split('/').map(Number); const N = Math.pow(2, z); const validX = x >= 0 && x < N; const validY = y >= 0 && y < N; const validZ = z >= 0 && z <= MAX_TILE_ZOOM; return validX && validY && validZ; }); tilesToLoad.forEach((tile) => { if (tiles[tile]) { return; // already loaded, no need to fetch } tiles[tile] = []; // temp hold for request // load every tile in the worker, so all the feature ids come from the same place tileWorker.postMessage({ tile, layers: LAYERS, url: TILE_SERVER_URL }); }); } let matrix; function updateMatrix() { const cameraMat = mat3.create(); // translate mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]); // scale const zoomScale = 1 / Math.pow(2, camera.zoom); const widthScale = TILE_SIZE / canvas.width; const heightScale = TILE_SIZE / canvas.height; mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]); // update matrix matrix = mat3.multiply( [], mat3.create(), // identity matrix mat3.invert([], cameraMat) // invert camera position ); needsPick = true; // map moved, so there could be something new under the mouse } // show the properties of the hovered feature in a popup function updatePopup() { const feature = features[hoveredId]; if (!feature) { popup.style.display = 'none'; popupId = 0; return; } // only rebuild the content when the feature changes if (popupId !== hoveredId) { popupId = hoveredId; const title = document.createElement('div'); title.className = 'popup-title'; title.textContent = feature.layer; popup.replaceChildren(title); Object.keys(feature.properties).forEach((key) => { const row = document.createElement('div'); const label = document.createElement('span'); label.className = 'popup-key'; label.textContent = `${key}: `; row.append(label, String(feature.properties[key])); popup.appendChild(row); }); } // position next to the mouse, but keep it inside of the map popup.style.display = 'block'; const left = Math.min(mouse.x + 12, canvas.width - popup.offsetWidth); const top = Math.min(mouse.y + 12, canvas.height - popup.offsetHeight); popup.style.left = `${left}px`; popup.style.top = `${top}px`; } ////////////////////// // helpers ////////////////////// function getClipSpacePosition(e) { // handle mouse and touch events const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left; const cssY = y - rect.top; // get normalized 0 to 1 position across and down canvas const normalizedX = cssX / canvas.clientWidth; const normalizedY = cssY / canvas.clientHeight; // convert to clip space const clipX = normalizedX * 2 - 1; const clipY = normalizedY * -2 + 1; return [clipX, clipY]; } // get the pixel on the canvas for a mouse or touch event function getCanvasPosition(e) { const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position (minus the border) const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left - canvas.clientLeft; const cssY = y - rect.top - canvas.clientTop; // convert to pixels, in case the canvas is being scaled const pixelX = Math.floor(cssX * canvas.width / canvas.clientWidth); const pixelY = Math.floor(cssY * canvas.height / canvas.clientHeight); return { x: Math.max(0, Math.min(pixelX, canvas.width - 1)), y: Math.max(0, Math.min(pixelY, canvas.height - 1)), }; } // get bbox coordinates for viewport function getBounds() { const zoomScale = Math.pow(2, camera.zoom); // undo clip-space const px = (1 + camera.x) / 2; const py = (1 - camera.y) / 2; // get world coord in px const wx = px * TILE_SIZE; const wy = py * TILE_SIZE; // get zoom px const zx = wx * zoomScale; const zy = wy * zoomScale; // get bottom-left and top-right pixels let x1 = zx - (canvas.width / 2); let y1 = zy + (canvas.height / 2); let x2 = zx + (canvas.width / 2); let y2 = zy - (canvas.height / 2); // convert to world coords x1 = x1 / zoomScale / TILE_SIZE; y1 = y1 / zoomScale / TILE_SIZE; x2 = x2 / zoomScale / TILE_SIZE; y2 = y2 / zoomScale / TILE_SIZE; // get LngLat bounding box const bbox = [ Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180), Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05), Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180), Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05), ]; return bbox; } function atLimits() { const bbox = getBounds(); return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05; } ////////////////////// // main program ////////////////////// let hammer; let handlePan; let handleZoom; let handleHover; let handleLeave; let timestamp; let slowCount; const run = (canvasId, abort) => { // setup loop state loopRunning = true; timestamp = 0; slowCount = 0; // create stats object for widget const stats = new Stats(); // get GL context from canvas canvas = document.getElementById(canvasId); gl = canvas.getContext("webgl"); // get overlay overlay = document.getElementById(`${canvasId}-overlay`); // create popup (hidden until something is hovered) popup = document.createElement('div'); popup.className = 'webgl-map-popup'; popup.style.display = 'none'; canvas.parentElement.appendChild(popup); popupId = 0; // setup tile worker // (only once, since the worker is keeping track of the feature ids) if (!tileWorker) { tileWorker = new Worker(new URL('./picking-tile-worker.js', import.meta.url)); tileWorker.onmessage = (event) => { const { tile, tileData } = event.data; tiles[tile] = tileData; // add features from the tile to the lookup (tileData || []).forEach((tileLayer) => { Object.assign(features, tileLayer.features); }); needsPick = true; // tile loaded, so there could be something new under the mouse }; tileWorker.onerror = (error) => { console.error('Uncaught worker error.', error); }; } // setup initial state updateMatrix(); updateTiles(); // setup viewport gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // compile shaders const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource); const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource); // init gl program const program = createProgram(gl, vertexShader, fragmentShader); gl.useProgram(program); gl.clearColor(0, 0, 0, 0); // lookup attributes and uniforms const positionAttributeLocation = gl.getAttribLocation(program, "a_position"); const pickColorAttributeLocation = gl.getAttribLocation(program, "a_pickColor"); const matrixLocation = gl.getUniformLocation(program, "u_matrix"); const colorLocation = gl.getUniformLocation(program, "u_color"); const pickingLocation = gl.getUniformLocation(program, "u_picking"); const hoveredColorLocation = gl.getUniformLocation(program, "u_hoveredColor"); const highlightColorLocation = gl.getUniformLocation(program, "u_highlightColor"); // highlight color is always the same gl.uniform4fv(highlightColorLocation, HIGHLIGHT_COLOR.map(n => n / 255)); // create buffers const positionBuffer = gl.createBuffer(); const pickColorBuffer = gl.createBuffer(); // create a texture to render the pick colors into (same size as the canvas) pickTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, pickTexture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); // create a framebuffer, and attach the texture to it pickFramebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, pickTexture, 0); gl.bindFramebuffer(gl.FRAMEBUFFER, null); // back to the canvas // render the tiles in view, to either the canvas or the picking buffer const drawTiles = (picking) => { gl.uniform1i(pickingLocation, picking ? 1 : 0); tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { layer, vertices, pickColors } = tileLayer; if (LAYERS[layer]) { const color = LAYERS[layer].map(n => n / 255); // set color uniform for layer gl.uniform4fv(colorLocation, color); // create buffer for vertices gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); // setup position attribute gl.enableVertexAttribArray(positionAttributeLocation); // tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER) let size = 2; let type = gl.FLOAT; let normalize = false; const stride = 0; let offset = 0; gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset); // create buffer for pick colors gl.bindBuffer(gl.ARRAY_BUFFER, pickColorBuffer); gl.bufferData(gl.ARRAY_BUFFER, pickColors, gl.STATIC_DRAW); // setup pick color attribute gl.enableVertexAttribArray(pickColorAttributeLocation); // each color is 4 bytes (RGBA), normalized from 0 - 255 to 0 - 1 size = 4; type = gl.UNSIGNED_BYTE; normalize = true; gl.vertexAttribPointer(pickColorAttributeLocation, size, type, normalize, stride, offset); // draw const primitiveType = gl.TRIANGLES; offset = 0; const count = vertices.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // find the id of the feature under the mouse const pick = () => { // render to the picking buffer instead of the canvas gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer); gl.clear(gl.COLOR_BUFFER_BIT); drawTiles(true); // webgl has the origin at the bottom-left, so flip the y const x = mouse.x; const y = canvas.height - mouse.y - 1; // read the color of the pixel under the mouse const pixel = new Uint8Array(4); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); // go back to rendering to the canvas gl.bindFramebuffer(gl.FRAMEBUFFER, null); return colorToId(pixel); }; const draw = () => { stats.begin(); // set matrix as uniform gl.uniformMatrix3fv(matrixLocation, false, matrix); // only pick when something has changed if (needsPick) { hoveredId = (mouse && !dragging) ? pick() : 0; needsPick = false; updatePopup(); } // tell the shader which feature to highlight gl.uniform4fv(hoveredColorLocation, idToColor(hoveredId).map(n => n / 255)); // render tiles drawTiles(false); overlay.replaceChildren(); // clear labels to redraw // tile boundaries aren't features, so they don't have a pick color gl.disableVertexAttribArray(pickColorAttributeLocation); gl.vertexAttrib4f(pickColorAttributeLocation, 0, 0, 0, 0); // render boundaries and label for tiles in view tilesInView.forEach((tile) => { gl.uniform4fv(colorLocation, [1, 0, 0, 1]); const tileVertices = geometryToVertices(tilebelt.tileToGeoJSON(tile)); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, tileVertices, gl.STATIC_DRAW); // setup position attribute gl.enableVertexAttribArray(positionAttributeLocation); // tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER) const size = 2; const type = gl.FLOAT; const normalize = false; const stride = 0; let offset = 0; gl.vertexAttribPointer(positionAttributeLocation, size, type, normalize, stride, offset); // draw const primitiveType = gl.LINES; offset = 0; const count = tileVertices.length / 2; gl.drawArrays(primitiveType, offset, count); // draw tile labels const tileCoordinates = tilebelt.tileToGeoJSON(tile).coordinates; const topLeft = tileCoordinates[0][0]; const [x, y] = MercatorCoordinate.fromLngLat(topLeft); const [clipX, clipY] = vec3.transformMat3( [], [x, y, 1], matrix, ); const wx = ((1 + clipX) / 2) * canvas.width; const wy = ((1 - clipY) / 2) * canvas.height; const div = document.createElement("div"); div.className = "tile-label"; div.style.left = (wx + 8) + "px"; div.style.top = (wy + 8) + "px"; div.style.position = 'absolute'; div.style.zIndex = 1000; div.style.pointerEvents = 'none'; // dont block the mouse from the canvas div.appendChild(document.createTextNode(tile.join('/'))); overlay.appendChild(div); }); // kill loop if gets too slow // 10 frames under 10 FPS const now = performance.now(); const fps = 1 / ((now - timestamp) / 1000); if (fps < 10) { slowCount++; if (slowCount > 10) { console.warn(`Too slow. Killing loop for ${canvasId}.`); stop(); if (abort) { abort(); } } } timestamp = now; // end of loop stats.end(); if (loopRunning) { frame = window.requestAnimationFrame(draw); } } frame = window.requestAnimationFrame(draw); // start loop //////////////////////// // interaction handlers //////////////////////// // handle touch events const Hammer = require('hammerjs'); hammer = new Hammer(canvas); hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL }); hammer.get('pinch').set({ enable: true }); // keep track of the mouse position for picking handleHover = (event) => { mouse = getCanvasPosition(event); needsPick = true; }; canvas.addEventListener('mousemove', handleHover); hammer.on('tap', handleHover); // no hover on mobile, so use tap handleLeave = () => { mouse = null; needsPick = true; }; canvas.addEventListener('mouseleave', handleLeave); // handle pan events let startX; let startY; // handle drag changes while mouse is still down const handleMove = (moveEvent) => { const [x, y] = getClipSpacePosition(moveEvent); // compute the previous position in world space const [preX, preY] = vec3.transformMat3( [], [startX, startY, 0], mat3.invert([], matrix) ); // compute the new position in world space const [postX, postY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // move that amount, because how much the position changes depends on the zoom level const deltaX = preX - postX; const deltaY = preY - postY; if (isNaN(deltaX) || isNaN(deltaY)) { return; // abort } // only update within world limits camera.x += deltaX; camera.y += deltaY; // update matrix with new camera updateMatrix(); // prevent further pan if at limits if (atLimits()) { camera.x -= deltaX; camera.y -= deltaY; updateMatrix(); return; // abort } // save current pos for next movement startX = x; startY = y; updateMatrix(); updateTiles(); } handlePan = (startEvent) => { // get position of initial drag [startX, startY] = getClipSpacePosition(startEvent); canvas.style.cursor = 'grabbing'; // no picking while the map is being dragged dragging = true; needsPick = true; if (startEvent.pointerType === 'touch') { mouse = null; // last tap is no longer over the same spot } window.addEventListener('mousemove', handleMove); hammer.on('pan', handleMove); // clear on release const clear = (event) => { canvas.style.cursor = 'grab'; dragging = false; needsPick = true; window.removeEventListener('mousemove', handleMove); window.removeEventListener('mouseup', clear); hammer.off('pan', handleMove); hammer.off('panend', clear); }; window.addEventListener('mouseup', clear); hammer.on('panend', clear); } canvas.addEventListener('mousedown', handlePan); hammer.on('panstart', handlePan); // handle zoom events handleZoom = (wheelEvent) => { wheelEvent.preventDefault(); const [x, y] = getClipSpacePosition(wheelEvent); // get position before zooming const [preZoomX, preZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // update current zoom state const prevZoom = camera.zoom; const zoomDelta = -wheelEvent.deltaY * (1 / 500); camera.zoom += zoomDelta; camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM)); updateMatrix(); // prevent further zoom if at limits if (atLimits()) { camera.zoom = prevZoom updateMatrix(); return; } // get new position after zooming const [postZoomX, postZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // camera needs to be translated the difference of before and after camera.x += preZoomX - postZoomX; camera.y += preZoomY - postZoomY; updateMatrix(); updateTiles(); } canvas.addEventListener('wheel', handleZoom); hammer.on('pinch', handleZoom); // setup stats widget stats.showPanel(0); // frame rate statsWidget = stats.dom; statsWidget.style.position = 'absolute'; statsWidget.style.zIndex = '0'; canvas.parentElement.appendChild(statsWidget); }; export const stop = () => { loopRunning = false; window.cancelAnimationFrame(frame); if (!canvas) { return; // not running, nothing to clean up } // clear event handlers canvas.removeEventListener('wheel', handleZoom); canvas.removeEventListener('mousedown', handlePan); canvas.removeEventListener('mousemove', handleHover); canvas.removeEventListener('mouseleave', handleLeave); hammer.destroy(); // clear DOM elements overlay.replaceChildren(); statsWidget.remove(); popup.remove(); // clear picking buffer gl.deleteFramebuffer(pickFramebuffer); gl.deleteTexture(pickTexture); canvas = null; mouse = null; hoveredId = 0; }; export default run;

Hovering a feature now shows which layer it belongs to, along with any properties that came with it in the tile (on mobile, tap a feature instead). There isn't a ton of metadata in these layers (buildings just have a height, for instance), but anything in the tile will show up here.

That's about it for picking. If you have any questions or comments, feel free to get in touch.

Mapping data is provided by OpenStreetMap contributors.