MapSnippets logoMapSnippets logo

Export Map as PNG with OpenLayers

OpenLayers

Capture the current OpenLayers map view as a downloadable PNG image using the canvas export API.

progress_activityLoading map...
var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', attributions: '&copy; <a href="https://www.maptiler.com/copyright/">MapTiler</a>' }) })
  ],
  view: new ol.View({ center: ol.proj.fromLonLat([2.3522, 48.8566]), zoom: 13 })
});
function exportMap() {
  map.once('rendercomplete', function() {
    var canvas = document.querySelector('#map canvas');
    if (canvas) {
      var link = document.createElement('a');
      link.download = 'map-export.png';
      link.href = canvas.toDataURL('image/png');
      link.click();
    }
  });
  map.renderSync();
}

How it works

OpenLayers renders the map on an HTML Canvas element. The rendercomplete event fires once all tiles and layers have been drawn, making it safe to capture the canvas content.

map.renderSync() forces an immediate render. After rendering completes, canvas.toDataURL() converts the canvas pixels to a PNG data URL. A temporary link element triggers the browser download dialog.

The map.once() method ensures the event listener fires only once per export, preventing duplicate downloads.

Key APIs

API Description Docs
rendercomplete event Fires when all layers finish rendering openlayers.org
map.renderSync() Force synchronous render openlayers.org
canvas.toDataURL() Convert canvas to image data URL MDN

FAQ

Why does the export sometimes produce a blank image?

Tiles from external servers may have CORS restrictions. The canvas becomes “tainted” and toDataURL() fails silently. Ensure the tile source supports CORS headers.

Can I export at a higher resolution?

Yes. Set a pixelRatio on the map or use ol.Map’s getSize() and render to an off-screen canvas at a larger size.

Common mistakes

  • Calling toDataURL() before tiles finish loading: always wait for the rendercomplete event
  • Forgetting map.renderSync(): without it, the render may not trigger immediately
  • Not selecting the correct canvas element: OpenLayers may create multiple canvas elements within the map container
auto_awesome

Build maps using OpenLayers with AI

Generate code like this export map as png with openlayers example using the OpenLayers skill in your IDE.

Related Examples