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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With