我想打印我网站的谷歌地图(不是页面的其余部分),它应包括标记,折线,infoWindows。
常用的方法是使用window.print()
,但这会打印整个页面,有没有办法只打印特定的地图或div?
我已经看到人们隐藏整个页面,除了渲染的div,但这似乎有点过分。
答案 0 :(得分:1)
我找到了一种使用html2canvas和popout:
组合的方法首先,我使用html2canvas渲染GoogleMap(或渲染div)。
然后我打开一个带有地图或div大小的新窗口,我在窗口中添加了一个img标签,并将画布URI(在第一步中渲染)作为图像数据。
最后,我用window.print()
打印弹出窗口,然后关闭弹出窗口。
这是我的js函数(包括html2canvas lib):
function printDiv(divId){
// For GoogleMaps I ignore the helps messages (.gm-style-pbc) displayed over the GoogleMap
$(".gm-style-pbc").each(function(){this.setAttribute("data-html2canvas-ignore","true");});
html2canvas($('#'+divId),
{
useCORS: true, // useCORS for GoogleMap or divs that use resources from outside the website
onrendered: function (canvas) {
// Can be tweaked to avoid popout being blocked
var myWindow=window.open("about:blank","popup"," width="+canvas.width+", height="+ canvas.height + "resizable=0,scrollbar=0");
if (myWindow == null){
//If popout has been blocked display a error message here
}else{
//Creating empty window with rendred div image URI
var content = "<!DOCTYPE html>";
content += "<html><head><title>Map</title></head><body>"
content += "<img src="+canvas.toDataURL()+"></img>"
content += "</body></html>"
myWindow.document.open()
myWindow.document.write(content);
myWindow.document.close();
myWindow.focus();
//Added a 500 ms timer before printing and closing as GoogleChrome sometimes didnt had time to render the image and printed a blank screen
setTimeout(function(){myWindow.print();myWindow.close();},500);
}
}
});
}
一些注意事项:
我的法国应用程序的屏幕截图: