html2canvas does not work with Google Maps Pan

Aaron Kreider picture Aaron Kreider · Jun 4, 2014 · Viewed 16.8k times · Source

I'm using html2canvas to save my online map as an image (See the Save as Image link). I've tried it in Firefox, Chrome and Opera.

It tends to work more often if you do not alter the default map. If you zoom and then pan the map, it is less likely to work. The map will pan, but html2canvas will use the old center point and map bounds. And html2canvas will fail to load map tiles for the new map bounds.

The map pans correctly, but html2canvas uses the old center point and map bounds. Why is this?

To support getting images from different domains I have the setting:

useCors: true;

I have tried the following solutions

-Manually changing the map type. Sometimes this fixes it.

-Triggering the browser resize event - not useful.

-Using setTimeout() to wait 2000 ms to ensure the tiles are loaded - not useful

-Using a proxy (html2canvas_proxy_php.php) - not useful

-Using the google maps idle event to wait for the map to be idle before saving - not useful

Answer

mfirdaus picture mfirdaus · Jun 18, 2014

Apparently, the problem seems to stem from html2canvas not being able to render css transforms, at least in chrome (I could only reproduce the problem in chrome, on OSX). The container that holds the tiles, is translated using -webkit-transform. So what we could do is to grab the values that the container is shifted, remove the transform, assign left and top from the values we got off transform then use html2canvas. Then so the map doesn't break, we reset the map's css values when html2canvas is done.

So I pasted this into the javascript console at your site and at it seemed to work

//get transform value
var transform=$(".gm-style>div:first>div").css("transform")
var comp=transform.split(",") //split up the transform matrix
var mapleft=parseFloat(comp[4]) //get left value
var maptop=parseFloat(comp[5])  //get top value
$(".gm-style>div:first>div").css({ //get the map container. not sure if stable
  "transform":"none",
  "left":mapleft,
  "top":maptop,
})
html2canvas($('#map-canvas'),
{
  useCORS: true,
  onrendered: function(canvas)
  {
    var dataUrl= canvas.toDataURL('image/png');
    location.href=dataUrl //for testing I never get window.open to work
    $(".gm-style>div:first>div").css({
      left:0,
      top:0,
      "transform":transform
    })
  }
});