TransWikia.com

Adding a map legend to a webpage

Geographic Information Systems Asked by Kimball on January 26, 2021

On the web page where the map shows (using Mapbox GL) and I want to add legend. The icons in the mapbox map are in a sprite with the details in JSON. I can see the PNG sprite and JSON in the browser console. The JSON looks like:

"airport-15": {
"width": 42,
"height": 42,
"x": 76,
"y": 300,
"pixelRatio": 2,
"visible": true
}

What’s the best way to create a CSS class for the marker icons? For performance reasons I’m hoping to avoid loading the PNG image a second time.
.icon-airport-15 {...}

Mapbox sprite documentation

One Answer

This code snippet might be helpful:

https://github.com/orangemug/legend-symbol/blob/master/src/util.js#L78-L102

export function mapImageToDataURL (map, icon) {
  if (!icon) {
    return undefined;
  }

  const image = map.style.imageManager.images[icon];
  if (!image) {
    return undefined;
  }

  const canvasEl = document.createElement("canvas");
  canvasEl.width = image.data.width;
  canvasEl.height = image.data.height;
  const ctx = canvasEl.getContext("2d");
  ctx.putImageData(
    new ImageData(
      Uint8ClampedArray.from(image.data.data),
      image.data.width, image.data.height
    ),
    0, 0
  );

  // Not toBlob() because toDataURL is faster and synchronous.
  return canvasEl.toDataURL();
}

Answered by Matt Bertrand on January 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP