0

I've tried creating the google map to image using html2canvas js and it is not working. I'm getting the error on console as "Element is not attached to a Document".

I've tried multiple functions of js for creating the canvas but none seems to work.

I've created images from canvas so if I can create the map into canvas this would also help.

Here '#closest_map' is the google map generated. PLz go through my snippets and suggest what's going wrong.

<html>

<head></head>

<body>
  <script>
    ///all the below snippets givs the same result
    var element = $("#closest_map");
    html2canvas(element, {
      useCORS: true,
      onrendered: function(canvas) {
        var dataUrl = canvas.toDataURL("image/png");
        document.write('<img src="' + dataUrl + '"/>');
      }
    });

    html2canvas($('#closest_map').get(0)).then(function(canvas) {
      var base64encodedstring = canvas.toDataURL("image/jpeg", 1);
      $('#img').attr('src', base64encodedstring);
    });
  </script>
</body>

</html>

Update I was able to create the images by using version html2canvas 4.0 js but now the marker which were circle in shape doesn't render out perfect circles. If a use a slightly higher JS like 5.0 I get the perfect circles but the map does not show up. just a cream coloured square holding my markers.

  • No, the $("#closest_map") is the div where I've created the google map. And I'm running the html2canvas function on button click and it is inside a function. – shubham kakade Jul 08 '19 at 08:41
  • 1
    The statement `var element = $("#closest_map");` will only work if the HTML of the canvas is BEFORE the script. It is not clear in your code. Please click [edit](https://stackoverflow.com/posts/56930899/edit) then the `[<>]` snippet editor for a [mcve] – mplungjan Jul 08 '19 at 08:46
  • yes the div with id "#closest_map" is before the script. I'm sorry I can't produce the code properly the code is big and the stack overflow rules for code format giving lot of errors. So I managed to put what's possible. – shubham kakade Jul 08 '19 at 08:55
  • `document.write('');` is a huge nono. You cannot ever use document.write after page load – mplungjan Jul 08 '19 at 08:57
  • Also there is no code that grabs any map. Also I do not see any jQuery js tags – mplungjan Jul 08 '19 at 08:58
  • I've included evry thing but on posting the snippet the stack overflow code formatter was giving a lot of formatting issues so I only posted the js code to create image. – shubham kakade Jul 08 '19 at 08:58
  • The '#closest_map' is the div where map is been generated I'm trying to convert the html to canvas which I have by html2canvas js which I've included. Thnaks for quick responce. – shubham kakade Jul 08 '19 at 09:01
  • Possible duplicate of https://stackoverflow.com/questions/56884126/cannot-convert-google-map-to-image-using-html2canvas/56888593#56888593 – MrUpsidown Jul 08 '19 at 11:26

0 Answers0