Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

jquery - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...