ScreenshotNeo

BlogHow-to

How to Export Leaflet Maps with GeoJSON Layers to PNG in Angular

Export a Leaflet map and GeoJSON overlays from Angular with Canvas, CORS-safe tiles, attribution, troubleshooting, and a complete working example.

By the ScreenshotNeo team30 September 20269 min read

How to Export Leaflet Maps with GeoJSON Layers to PNG in Angular

To export a Leaflet map with GeoJSON layers to PNG in Angular, keep the Leaflet map instance in the component that owns it, render every exported vector layer with Canvas, wait for tiles and other assets to load, then pass the map to leafletImage. The callback returns a canvas that you can download as a PNG.

The difficult parts are usually rendering mode and browser security rather than Angular itself. Leaflet paths rendered as SVG are not collected by leaflet-image on Leaflet 1+, and a tile or marker image without compatible CORS headers can make the canvas unreadable. HTML controls, legends, and divIcon markers also need separate handling because they are not rasterized by leaflet-image.

What the export pipeline does

  1. Obtain the real L.Map instance from your Angular component or ngx-leaflet map reference.
  2. Create GeoJSON with L.geoJSON(data, options), and set renderer: L.canvas() for every vector layer that must appear in the image.
  3. Add the basemap and overlays in the intended order. Use panes when you need explicit z-order.
  4. Set the view with setView or frame the data with fitBounds.
  5. Wait until required tiles and image assets have loaded.
  6. Call leafletImage(map, callback), convert the returned canvas to a PNG data URL or Blob, and trigger a download.
  7. Keep the map provider’s required attribution in the exported result.

This is the browser-side workflow documented by leaflet-image. Leaflet’s reference documents GeoJSON layers and Canvas rendering, while its pane example shows how to control ordering and use fitBounds.

The Angular export flow: prepare Canvas layers, wait for assets, then encode the returned canvas as PNG.
The Angular export flow: prepare Canvas layers, wait for assets, then encode the returned canvas as PNG.

Install the Angular and Leaflet dependencies

The exact package versions must match your application. This example assumes Leaflet, its type definitions, and leaflet-image are already compatible with your Angular build.

npm install leaflet leaflet-image
npm install --save-dev @types/leaflet

Import Leaflet’s stylesheet in angular.json or your global stylesheet so the map has the expected dimensions and controls:

/* styles.css */
@import "leaflet/dist/leaflet.css";

#map {
  height: 520px;
  width: 100%;
}

In TypeScript, leaflet-image may not ship the type declaration your project expects. A small declaration file keeps strict TypeScript builds clear:

// src/types/leaflet-image.d.ts
declare module 'leaflet-image' {
  import * as L from 'leaflet';
  type Callback = (error: Error | null, canvas: HTMLCanvasElement) => void;
  export default function leafletImage(map: L.Map, callback: Callback): void;
}

Complete Angular component

The following component demonstrates a basemap, a GeoJSON feature collection, Canvas rendering, a dedicated pane, a tile-load wait, and a PNG download. Replace the tile URL and GeoJSON with services permitted for your application. The tile layer’s crossOrigin setting helps the browser request images in CORS mode, but the tile server must also send suitable response headers.

import { Component, OnDestroy, AfterViewInit } from '@angular/core';
import * as L from 'leaflet';
import leafletImage from 'leaflet-image';

@Component({
  selector: 'app-map-export',
  template: `
    <div id="map"></div>
    <button type="button" (click)="exportPng()" [disabled]="exporting">
      {{ exporting ? 'Preparing…' : 'Download PNG' }}
    </button>
    <p *ngIf="errorMessage" role="alert">{{ errorMessage }}</p>
  `
})
export class MapExportComponent implements AfterViewInit, OnDestroy {
  private map!: L.Map;
  private tiles!: L.TileLayer;
  private geoJson!: L.GeoJSON;
  exporting = false;
  errorMessage = '';

  private data: GeoJSON.FeatureCollection = {
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        properties: { name: 'Example area' },
        geometry: {
          type: 'Polygon',
          coordinates: [[
            [-73.99, 40.72],
            [-73.97, 40.72],
            [-73.97, 40.74],
            [-73.99, 40.74],
            [-73.99, 40.72]
          ]]
        }
      }
    ]
  };

  ngAfterViewInit(): void {
    this.map = L.map('map', {
      // This applies Canvas as the default renderer for vector layers.
      preferCanvas: true
    }).setView([40.73, -73.98], 13);

    this.tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      crossOrigin: true,
      attribution: '&copy; OpenStreetMap contributors'
    }).addTo(this.map);

    this.map.createPane('geojson-pane');
    this.map.getPane('geojson-pane')!.style.zIndex = '450';

    this.geoJson = L.geoJSON(this.data, {
      pane: 'geojson-pane',
      renderer: L.canvas(),
      style: {
        color: '#155eef',
        weight: 3,
        fillColor: '#84adff',
        fillOpacity: 0.35
      }
    }).addTo(this.map);

    // Use this when the export should frame all features:
    // this.map.fitBounds(this.geoJson.getBounds(), { padding: [20, 20] });
  }

  async exportPng(): Promise<void> {
    if (!this.map || !this.geoJson) return;

    this.exporting = true;
    this.errorMessage = '';

    try {
      await this.waitForTiles();
      await new Promise<void>((resolve, reject) => {
        leafletImage(this.map, (error, canvas) => {
          if (error) {
            reject(error);
            return;
          }

          canvas.toBlob(blob => {
            if (!blob) {
              reject(new Error('The browser could not create a PNG blob.'));
              return;
            }

            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'leaflet-map.png';
            link.click();
            URL.revokeObjectURL(url);
            resolve();
          }, 'image/png');
        });
      });
    } catch (error) {
      this.errorMessage = error instanceof Error
        ? error.message
        : 'Map export failed.';
    } finally {
      this.exporting = false;
    }
  }

  private waitForTiles(): Promise<void> {
    return new Promise(resolve => {
      if (this.tiles.isLoaded()) {
        resolve();
        return;
      }
      this.tiles.once('load', () => resolve());
      // Avoid waiting forever when a remote tile fails.
      window.setTimeout(resolve, 15000);
    });
  }

  ngOnDestroy(): void {
    this.map?.remove();
  }
}

For a production application, replace the timeout fallback with your own readiness policy if a missing tile should fail the export. The important point is that the export runs after the map exists and after the assets your image depends on are ready.

GeoJSON styling, framing, and layer order

Force Canvas on every included vector layer

Setting preferCanvas: true on the map is a useful default, but set renderer: L.canvas() explicitly on GeoJSON and other paths that must be exported. This avoids accidentally creating an SVG layer that leaflet-image cannot collect under its Leaflet 1+ requirements.

const roads = L.geoJSON(roadsData, {
  renderer: L.canvas(),
  style: feature => ({
    color: feature?.properties?.kind === 'primary' ? '#d12f2f' : '#555',
    weight: 2,
    opacity: 0.9
  })
}).addTo(this.map);

Frame the features

When the desired image should show all GeoJSON features, use the layer bounds after adding it:

this.map.fitBounds(this.geoJson.getBounds(), {
  padding: [24, 24],
  maxZoom: 15
});

If your data can be empty, check getBounds().isValid() before calling fitBounds. Otherwise the map may jump to an unusable view.

Control z-order with panes

Leaflet panes let you put labels, boundaries, and fills in a predictable order. Create panes before adding layers, assign a numeric zIndex, and keep related layers in the same pane policy. The Leaflet map panes example demonstrates this approach.

this.map.createPane('labels');
this.map.getPane('labels')!.style.zIndex = '650';

L.geoJSON(labelGeometry, {
  pane: 'labels',
  renderer: L.canvas(),
  style: { color: '#111', weight: 1 }
}).addTo(this.map);

Waiting for tiles and other assets

Calling the exporter immediately after addTo can produce a blank or incomplete basemap. Listen for the tile layer’s load event, or track each required layer if your map uses multiple tile sources. Marker images also need to be loaded before export.

Do not assume that a successful HTTP response means the browser can read the pixels. A canvas becomes tainted when it draws disallowed cross-origin content. In that state, toDataURL and toBlob fail even though the map looked correct on screen.

Asset What to verify Typical result when it is wrong
Basemap tiles CORS-compatible response headers and a matching crossOrigin request Missing tiles, tainted canvas, or export error
Image markers Image URL and CORS support Marker omitted or canvas cannot be read
GeoJSON paths Canvas renderer on each included vector layer Basemap appears but polygons or lines do not
HTML overlays Separate composition strategy Controls, legends, and divIcon markers are absent

What leaflet-image includes and excludes

leaflet-image is a map-layer rasterizer, not a screenshot of the entire DOM. It can combine compatible tile images and Canvas-rendered Leaflet paths. It does not rasterize arbitrary HTML, including zoom controls, legends, HTML popups, or L.divIcon content.

If those elements are required, choose one of these designs:

  • Draw the missing labels or legend into a second canvas and composite it with the map canvas.
  • Use an export-specific Leaflet layer that represents the information as Canvas or image content.
  • Capture the rendered page with a browser screenshot service, then validate that service against your exact map, tile provider, and overlays.

A DOM screenshot library may capture HTML overlays while failing to reproduce external tiles or Canvas content. The historical Angular 5 report in the research describes that kind of split result; treat it as an anecdotal diagnostic clue, not a benchmark.

PNG dimensions, resolution, and large GeoJSON

The generated canvas follows the map’s rendered size. Set the map container dimensions before export if you need a predictable output, and avoid resizing the container during capture. For a higher-resolution image, render a dedicated export map at a larger CSS size or use a higher device pixel ratio in your own rendering strategy; verify memory use with your actual dataset.

Large GeoJSON collections can make layout, Canvas drawing, and PNG encoding slow. Practical measures include simplifying geometry before sending it to the browser, exporting a focused region instead of the entire dataset, removing invisible layers, and avoiding repeated exports for unchanged views. Measure with your real browser and data because the supplied research contains no authoritative cross-library benchmark.

Common errors and fixes

Symptom Cause Fix
Basemap exports, GeoJSON is missing The paths use SVG rendering Add renderer: L.canvas() to every exported vector layer and consider preferCanvas: true.
SecurityError from toDataURL or toBlob A tile or image asset tainted the canvas Use a CORS-compatible tile/image source, set the appropriate cross-origin request mode, and confirm response headers.
Blank or partial basemap Export started before tiles finished Wait for tile load events and handle failed tiles according to your policy.
Controls or legend are absent They are HTML, which leaflet-image does not rasterize Composite a separate canvas or use a screenshot workflow that supports the required DOM.
Features are behind another layer Pane or insertion order is unintended Create panes with explicit z-index values and assign each layer deliberately.
Export runs before the map exists Angular lifecycle timing Store the map in ngAfterViewInit or the wrapper’s map-ready callback, then enable the export button.
Output is empty for an empty dataset fitBounds received invalid bounds Check getBounds().isValid() and keep a sensible fallback view.

Attribution and operational checklist

Tile providers commonly require attribution. Leaflet and leaflet-image both indicate that generated images carry the same attribution obligation as the map. Put attribution in the image itself, in a surrounding report, or in the download’s accompanying metadata according to the provider’s terms. Do not remove it merely because the result is a PNG.

ScreenshotNeo removes common consent and overlay clutter before capturing a page.
ScreenshotNeo removes common consent and overlay clutter before capturing a page.
  • Map instance is created before export.
  • Every exported path uses Canvas.
  • GeoJSON style and pane assignments are applied before capture.
  • View or fitBounds is final.
  • Required tiles and marker images have loaded.
  • Tile and image hosts support the needed CORS behavior.
  • HTML controls and legends have a separate plan.
  • Attribution is preserved.
  • Large datasets are tested in the target browsers.

Or skip the browser setup

If you need a clean image of a public map page, ScreenshotNeo can capture a URL through one request. It removes cookie and consent banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for the complete option list, including viewport and device presets, full-page capture, CSS selectors, dark mode, custom CSS and JavaScript, waits, request blocking, headers, cookies, geolocation, caching, signed links, asynchronous jobs, bulk capture, and PDF output.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://your-map-page.example \
  -o map.png

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://your-map-page.example"},
    timeout=90,
)
r.raise_for_status()
open("map.png", "wb").write(r.content)

Node.js

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://your-map-page.example'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('map.png', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo has 1,000 screenshots per month free with no card. Paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.

FAQ

Can I export SVG-rendered GeoJSON with leaflet-image?

For Leaflet 1+, configure included vector layers with Canvas. SVG paths are not collected by leaflet-image’s documented workflow.

Why does the map display correctly but PNG creation fail?

Display and pixel readback are different operations. A cross-origin tile or image can display while tainting the canvas, causing toDataURL or toBlob to fail.

Will the PNG contain Leaflet controls?

No. Controls, legends, and other HTML overlays are outside leaflet-image’s rasterized map layers. Composite them separately or use a page screenshot workflow.

Should I use a server for every export?

Browser export is suitable when your tile and image sources support CORS and Canvas covers the required layers. A server-side capture service is useful when you need a repeatable URL capture or want to avoid browser and tile setup in your application.

How do I make an export reproducible?

Fix the map dimensions, zoom and center, GeoJSON styling, pane order, tile source, wait conditions, and attribution policy. Record failures separately from successful image generation so a missing tile is not mistaken for a valid map.