MapSnippets logo MapSnippets logo

Export Leaflet Map as PNG

Leaflet

Export the current Leaflet map view as a PNG by rendering the map container with html2canvas() and saving it with canvas.toDataURL().

progress_activity Loading map...
const map = L.map('map').setView([48.8566, 2.3522], 13);
L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
  tileSize: 256,
  attribution: '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
L.marker([48.8584, 2.2945]).addTo(map).bindPopup('Eiffel Tower');
document.getElementById('export-btn').addEventListener('click', () => {
  html2canvas(document.getElementById('map'), { useCORS: true }).then(canvas => {
    const link = document.createElement('a');
    link.download = 'map-export.png';
    link.href = canvas.toDataURL();
    link.click();
  });
});

How to export a Leaflet map as a PNG image

Exporting a Leaflet map to PNG requires capturing the rendered DOM as a canvas. The html2canvas library takes a screenshot of the map container by rendering its DOM into an HTML5 Canvas element. The useCORS: true option allows cross-origin tile images to be captured.

The export button triggers html2canvas, which returns a canvas element. Converting it to a data URL with canvas.toDataURL() and programmatically clicking a download link saves the image as map-export.png. Markers, popups, and overlays are included in the capture.

Key APIs

API Description Docs
html2canvas DOM-to-canvas renderer html2canvas.hertzen.com
canvas.toDataURL() Convert canvas to image MDN Canvas.toDataURL

FAQ

Why are tiles blank in the exported image?

Cross-origin tiles taint the canvas. Make sure useCORS: true is set and that the tile server sends proper CORS headers. MapTiler tiles support CORS.

Can I set a custom resolution for the export?

Pass scale: 2 to html2canvas options for a 2x resolution export (retina quality).

Common mistakes

  • Forgetting useCORS: true, which leaves tile images blank or taints the canvas
  • Trying to use leaflet-image without a bundler. html2canvas is simpler for CDN setups.
  • Exporting while tiles are still loading. Wait for the map.on('load') event before enabling the export button.

Build maps using Leaflet with AI

Generate code like this export leaflet map as png example using the Leaflet skill in your IDE.