Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API V3 Printing Maps

I am looking for a method to efficiently print Google maps that have been implemented on a site using the google maps api v3.

I have seen some people using just the window.print js and then

@media print
{
    body * { visibility: hidden; }
    #map * { visibility: visible; }
    #map {visibility: visible;position:absolute; top: 5px; left: 5px;}
}

Currently a larger map is displayed to users using fancybox and I have added a print button to this. Ideally I just want to add some jquery or similar to print the map.

However this doesn't seem to really work. Has anyone got any suggestions on the best way to do this

like image 310
Purple Hexagon Avatar asked Nov 28 '22 21:11

Purple Hexagon


1 Answers

I guess by simple yet subtle DOM manipulation, you can get the "snapshot" of your Google Maps (well, theoretically - any maps :)) viewer and perfectly print it in any browsers. Assuming $mapContainer is the main container of your maps, related code is:

// printAnyMaps ::
function printAnyMaps() {
  const $body = $('body');
  const $mapContainer = $('.map-container');
  const $mapContainerParent = $mapContainer.parent();
  const $printContainer = $('<div style="position:relative;">');

  $printContainer
    .height($mapContainer.height())
    .append($mapContainer)
    .prependTo($body);

  const $content = $body
    .children()
    .not($printContainer)
    .not('script')
    .detach();

  /**
   * Needed for those who use Bootstrap 3.x, because some of
   * its `@media print` styles ain't play nicely when printing.
   */
  const $patchedStyle = $('<style media="print">')
    .text(`
      img { max-width: none !important; }
      a[href]:after { content: ""; }
    `)
    .appendTo('head');

  window.print();

  $body.prepend($content);
  $mapContainerParent.prepend($mapContainer);

  $printContainer.remove();
  $patchedStyle.remove();
}

Note that you can flexibly replace $printContainer by any print template. Here I just use a simple <div> that serves as a placeholder of the snapshot.

Working code here: http://jsfiddle.net/glenn/6mx21ted

like image 72
Glenn Mohammad Avatar answered Dec 10 '22 07:12

Glenn Mohammad