Alex Rivera | Logout

Center Google Maps (V3) on browser print

Asked 2012-02-23T19:35:10.090
8

I have a map set to 100% of the page width. The map has one marker and is centered on that marker. When I print the browser, I want the map to stay centered on the marker. This is the code I wrote to do so:

var lastPos = map.getCenter();
google.maps.event.addListener(map, "idle", function() {
  lastPos = map.getCenter();
  console.log(lastPos.toString());
});      

google.maps.event.addDomListener(window, "resize", function() {
  google.maps.event.trigger(map, "resize"); 
  map.setCenter(lastPos);
  console.log("Re-center on " + lastPos.toString());
});

This works when I re-size my browser, but does not work when the browser re-sizes itself before printing. If my browser is above a certain width then the marker is shifted entirely off the page (to the right) when the map is printed.

Here is my test case: http://www-sf.talispoint.com/testmapprint.html

Edit
Report

1 Answer

7

You would need to add a @media print and give the map the size when printing and then you can do what is explained below.

When a map is printed what happens is that the top left corner is kept and the map is adjusted to fit the @media print size.

If you want the center to stay the same you need to manually change the center of the map. http://jsbin.com/owiwox/33 is an example on how to work around this.

It uses a listener for the print media being applied event and adjusts the center of the map using a ratio on how the map is changed (made smaller)

One thing that you have to take care of is that you might have to make this browser targeted to make it work on all browsers (This solution works well in Chrome) A good resource for making it work across browsers is: http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

The js code from the sample above listens to print requests and shifts the map so that the top left corner has the same center as the big map.

To cut the whole story short, this is how it works

  1. You need to put in the ratio of the map vs printed map (or get the size by checking it from JS) You assign it to: var widthRatio = 2; var heightRatio = 3;

  2. You listen for print media being applied and shift the center so that it does not change

  3. After you finish print , you revert the change.

Still here you have the problem that a part of the map will be cut, but there is not a good solution here, since the zoom level -1 tiles might not be cached so when you zoom out to fit bounds you might get no tiles.

answered 2013-04-18T13:13:41.597

Your Answer