Openlayers打印功能

时间:2013-08-29 19:12:11

标签: javascript openlayers

我想为我的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);
            }
        });
    };

3 个答案:

答案 0 :(得分:2)

尝试

function printFunction() {

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

这对我有用。 hashtag标识仅适用于jQuery,花了一段时间才弄明白: - )

但是有一个小问题。 html2canvas没有呈现背景WMS图层 - 只有地图窗口和标记,因此仍需要进行一些调整。

更新: 我已经做了一些摆弄这个,我认为它不适用于openlayers。由于openlayers地图是许多div的组合,因此html2canvas似乎无法正确绘制所有这些。特别是WMS层,当尝试单独绘制时,返回错误。您可以尝试在地图中渲染其中一个子div,但这对我没用。虽然,如果你只使用简单的矢量图形,它可能适合你。

答案 1 :(得分:1)

好的,我现在已经花了几个小时在这上面了,我提出的最好的是@ Kenny806答案的增强,基本上是this one

它确实似乎拿起了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上测试
  • 这是一个hacky解决方案(不幸的是,我正在努力为我的情况找到其他选择)
  • 如果您可以选择使用Openlayers 3,似乎有更好的画布支持,我也看到了令人信服的toBlob示例:http://codepen.io/barbalex/pen/raagKq

答案 2 :(得分:0)

WMS绘制工作正常,但您必须使用AJAX实现代理以下载WMS切片。请参阅html2canvas的PHP代理示例,了解“代理”的实现细节(不是http代理“。