Export Leaflet Map as PNG
LeafletCapture the current Leaflet map view as a downloadable PNG image using the html2canvas library.
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: '© <a href="https://www.maptiler.com/">MapTiler</a> © <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 it works
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. Ensure 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: tile images will be blank or the canvas will be tainted - Trying to use
leaflet-imagewithout 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.
Related Examples
- Initialize a Leaflet Map with MapTiler Tiles
- See how to do this in MapLibre GL JS, MapTiler SDK or OpenLayers