简体   繁体   中英

Resize Google Maps when printing

So im using this function to print my Google Maps API V3:

function printit(){
var content = window.document.getElementById("map-canvas");
var newWindow = window.open(); // open a new window
newWindow.document.write(content.innerHTML); // write the map into the new window
newWindow.print(); // print the new window
};

And this is the HTML button that im using:

<button onClick="printit()">Print</button>

The problem is that map-canvas is set to 100% width with CSS, so wen the map is printed only left side is visible (as much as it fits on A4 paper). I tryed adding this:

document.getElementById("map-canvas").style.width = "900px";

But i get an error. Can you help me with this?

The Google Maps API normally uses the ID map_canvas for the height and width properties instead of map-canvas . So it has to be:

document.getElementById("map_canvas").style.width = "900px";

尝试

google.maps.event.trigger(map, 'resize');

I found the solution, it was not as simple as i thought it would be, here is the complete working code, it was tested in Chrome, Firefox, Opera and it works perfectly:

<script type="application/javascript">
function printit(){
  var newWidth = 700,
    content = document.getElementsByClassName("gm-style")[0],
    translateX = (content.clientWidth - newWidth) / 2,
    orgTranslate = content.firstChild.firstChild.style.transform,
    left = content.firstChild.firstChild.style.left;

  var win = window.open();
  win.document.write(content.outerHTML);
  var c = win.document.getElementsByClassName("gm-style")[0];
  c.style.width = newWidth + "px";

    if (orgTranslate) {
    orgTranslate = orgTranslate.split(",");
    orgTranslate[4]-= translateX;
    c.firstChild.firstChild.style.transform = orgTranslate.join(",");
  } else {
    c.firstChild.firstChild.style.left = (parseInt(left, 10) - translateX) + "px"; // firefox uses absolute positioning
  }

  win.print();
};

var center;
function calculateCenter() {
  center = map.getCenter();
}
google.maps.event.addDomListener(map, 'idle', function() {
  calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
  map.setCenter(center);
});
</script>

And also the print button:

<button onClick="printit()">Print</button>

Hope this will help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM