Openlayers打印功能

Openlayers Print Function

本文关键字:功能 打印 Openlayers      更新时间:2023-09-26

我想为我的Openlayers地图创建一个打印按钮,它可以获取地图图像并创建一个漂亮的图像文件。我试过了http://dev.openlayers.org/sandbox/camptocamp/canvas/openlayers/examples/exportMapCanvas.html但它像实验一样缝合。我也看过http://trac.osgeo.org/openlayers/wiki/Printing但我不希望涉及任何服务器。我也退房了http://html2canvas.hertzen.com/但无法使其发挥作用。我得到以下错误,Uncaught TypeError:无法读取未定义的属性"images",html2canvas.js

<button onclick="printFunction()">Click me</button>
function printFunction() {
        html2canvas(('#map'), {
            onrendered: function (canvas) {
                var img = canvas.toDataURL("image/png")
                window.open(img);
            }
        });
    };

尝试

function printFunction() {
    html2canvas(document.getElementById("map"), {
        onrendered: function (canvas) {
            var img = canvas.toDataURL("image/png")
            window.open(img);
        }
    });

这对我有效。标签识别只对jQuery有效,我花了一段时间才弄清楚:-)

不过有一个小问题。html2canvas没有渲染背景WMS层,只有地图窗口和标记,因此仍需要进行一些调整。

更新:我对此做了一些修改,我认为它不会与开放层一起工作。由于openlayers地图是由许多div组成的,因此html2canvas似乎无法正确绘制所有div。特别是WMS图层,当尝试单独绘制时,会返回错误。你可以尝试渲染地图中的一个子div,但这对我来说不起作用。不过,如果你只使用简单的矢量图形,它可能对你起作用。

好吧,我已经花了几个小时在这上面了,我想出的最好的办法是对@Kenny806的答案进行了增强,基本上就是这个。

它似乎确实拾取了WMS和Vector层:

    function exportMap() {
        var mapElem = document.getElementById('map'); // the id of your map div here
        // html2canvas not able to render css transformations (the container holding the image tiles uses a transform)
        // so we determine the values of the transform, and then apply them to TOP and LEFT 
        var transform=$(".gm-style>div:first>div").css("transform");
        var comp=transform.split(","); //split up the transform matrix
        var mapleft=parseFloat(comp[4]); //get left value
        var maptop=parseFloat(comp[5]);  //get top value
        $(".gm-style>div:first>div").css({ //get the map container. not sure if stable
          "transform":"none",
          "left":mapleft,
          "top":maptop,
        });
        html2canvas(mapElem, {
          useCORS: true,
          onrendered: function(canvas) {
             mapImg = canvas.toDataURL('image/png');
            // reset the map to original styling
            $(".gm-style>div:first>div").css({
              left:0,
              top:0,
              "transform":transform
            });
            // do something here with your mapImg
            // e.g. I then use the dataURL in a pdf using jsPDF...
            // createPDFObject();
          }
        });
    }

票据

  • 仅在Chrome和Firefox上测试
  • 这是一个棘手的解决方案(不幸的是,我很难为自己的情况找到其他选择)
  • 如果你可以选择使用Openlayers 3,那么似乎有更好的画布支持,我也看到了一个令人信服的toBlob示例:http://codepen.io/barbalex/pen/raagKq

WMS绘制工作正常,但您必须使用AJAX实现用于下载WMS瓦片的代理。有关"代理"(不是http代理)的实现详细信息,请参阅html2canvas的PHP代理示例。