Search code examples
javascriptgoogle-mapsgoogle-maps-api-3google-maps-markersnew-window

Duplicate Google Maps DIV to new window for printing


Here is my situation. I have a map created using google maps API, with styling and a FusionTable overlay. The user can zoom into any location, and when he/she clicks on any polygon, an infoWindow pops-up with contact information. The user then would press on a 'Print' button that should open the map on a new window and initiate the print dialog box. Now, here is my two part question.

  1. How can I duplicate the google maps instance (zoomed-in with polygons and infowindow) to a new window.
  2. How can I trigger a print command after the map is rendered.

Now, here is a background of what I tried so far and the results.

  • Copied map to new window, but print command acts funny, as it goes beyond the 'div' parameters and breaks the map.
  • Tried the html2canvas method, but it only works as it should when you SHIFT+click the print button.

For bonus marks: When printing I would like to resize the map proportionally to fit the page size (it is currently cropping part of the map).


Solution

  • Finally managed to solve this, and so I am posting my solution to help anybody who might be requiring the same functionality. And also to open up any possibility for refinement. The main point is to target the "innerHTML" of the map div.

    Here is my function that will be triggered by the "Print" button located on the page:

    $('.map-print').on('click',
        function printMap() {
        var mapwindow = window.open('', 'PRINT');
        mapwindow.document.write('<!DOCTYPE html><html><head><title>' + document.title + ' Agent Finder Map</title><link rel="stylesheet" type="text/css" media="print" href="https://www.liteline.com/styles/print.css" />');
        mapwindow.document.write('<style>@media print { #map-canvas div > img { position: absolute; } }</style>'); //important in order to force the print render not to break apart causing a grayed-out band
        mapwindow.document.write('</head><body>');
        mapwindow.document.write('<div id="map-canvas" style="position:relative;width:1000px;height:670px;overflow:hidden !important">');
        mapwindow.document.write(document.getElementById("map-canvas").innerHTML);
        mapwindow.document.write('</div>');
        mapwindow.document.write('</body></html>');
        mapwindow.document.close();
        mapwindow.focus();
        mapwindow.print();
        mapwindow.close();
        return false;
    });
    

    I know it is not totally perfect, but it did the job. Hope that this solution might help someone.