1

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
              .match(/^matrix\(([^\(]*)\)$/)[1]
              .split(",")
              .map(Number);
            // Apply the transform to the export map context
            CanvasRenderingContext2D.prototype.setTransform.apply(
              mapContext,
              matrix
            );
            mapContext.drawImage(canvas, 0, 0);
          }
        }
      });

      var pdf = new jsPDF("landscape", undefined, "a4");
      pdf.addImage(mapCanvas.toDataURL("image/jpeg"), "JPEG", 0, 0, 297, 210);
      pdf.save("map.pdf");
      // Reset original map size
      this.map.setSize(size);
      this.map.getView().setResolution(viewResolution);
      document.body.style.cursor = "auto";
    });
    this.map.renderSync();
  }
  • 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.