public static async getImageFromMetadata()

in baremaps-renderer/src/lib/maplibreBrowserHelpers.ts [72:132]


  public static async getImageFromMetadata(
    page: Page,
    metadata: Metadata,
    styleUrl: string,
  ) {
    const width = metadata.width;
    const height = metadata.height;

    await page.setViewport({ width, height, deviceScaleFactor: 1 });
    await page.setContent(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <title>Query Test Page</title>
            <meta charset='utf-8'>
            <link rel="icon" href="about:blank">
            <style>#map {
                box-sizing:content-box;
                width:${width}px;
                height:${height}px;
            }</style>
        </head>
        <body>
            <div id='map'></div>
        </body>
        </html>`);

    // create map
    await page.evaluate(
      (metadata: Metadata, styleUrl: string) => {
        (window as any).map = new (window as any).maplibregl.Map({
          container: 'map',
          style: styleUrl,
          center: metadata.center,
          zoom: metadata.zoom,
          interactive: false,
          attributionControl: false,
          // If true, the map's canvas can be exported to a PNG using map.getCanvas().toDataURL(). This is false by default as a performance optimization.
          preserveDrawingBuffer: true,
          // Prevents the fading-in of layers after the style has loaded.
          fadeDuration: 0,
        });
      },
      metadata,
      styleUrl,
    );

    // wait for map to load
    await page.waitForFunction(() => {
      return (
        (window as any).map?.loaded() && (window as any).map?.isStyleLoaded()
      );
    });

    // export image from map
    const image = await page.evaluate(() => {
      return (window as any).map.getCanvas().toDataURL();
    });

    return Buffer.from(image.split(',')[1], 'base64');
  }