For my project I am trying to export the map I have created with all it's Vector layers. I can't seem to get the example I found on the site of OpenLayers to work in React. The export doesn't need to produce a PDF. It would be nice but if I can export a image file, that would be nice as well. It's just that I can't seem to get the code to work in React.

  exportMap() {
    this.map.once("rendercomplete", () => {
      var viewResolution = this.map.getView().getResolution();
      var mapCanvas = document.createElement("canvas");
      var size = this.map.getSize();
      mapCanvas.width = size[0];
      mapCanvas.height = size[1];
      var mapContext = mapCanvas.getContext("2d");

      this.map.getLayers().forEach((canvas) => {
        if (canvas !== undefined) {
          if (canvas.width > 0) {
            var opacity = canvas.parentNode.style.opacity;
            mapContext.globalAlpha = opacity === "" ? 1 : Number(opacity);
            var transform = canvas.style.transform;
            // Get the transform parameters from the style's transform matrix
            var matrix = transform
            // Apply the transform to the export map context
            mapContext.drawImage(canvas, 0, 0);

      var pdf = new jsPDF("landscape", undefined, "a4");
      pdf.addImage(mapCanvas.toDataURL("image/jpeg"), "JPEG", 0, 0, 297, 210);
      // Reset original map size
      document.body.style.cursor = "auto";
  • The solution is in OL's help openlayers.org/en/latest/examples/export-map.html – Fran Raga May 28 at 15:56
  • map.getLayers() returns OpenLayers layer objects, not their canvases. Canvases can be found using document.querySelectorAll('.ol-layer canvas') which returns a node list - or this.map.getViewport().querySelectorAll('.ol-layer canvas') might be more efficient in a large document. Unless you are supporting IE which doesn't implement NodeList.forEach() you can simply replace getLayers() with getViewport().querySelectorAll('.ol-layer canvas') – Mike May 30 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.