Skip to content Skip to sidebar Skip to footer

Save Google Map As An Image - Using Javascript (able To Take Screenshot)

I referred to the following SO questions to capture a screenshot of google maps using javascript (html2canvas). feedback.js, screen-capturing-using-html2canvas, create-screen-shot,

Solution 1:

I had problems with IE9 and, in Chrome, some images are downloaded but they are corrupted. The only solution I found for IE9 was opening the image on a new tab, then I was able to right click and save as. I made the next code for download the div area (container of the map) as an image using html2canvas.

 function download_image() {
    if($.browser.safari) {// Fix for Chrome
        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([$("#div_id")[0]], {
        logging: false,
        useCORS: true,
        onrendered: function (canvas) {
            if ($("#downloadimg").length > 0)
                $("#downloadimg").remove();
            var fileName = "file_name.png";
            if (/\bMSIE|Trident\b/.test(navigator.userAgent) && $.browser.version.match(/9.0|10.0|11.0/)) {//Only for IE 9, 10 and 11
                download_image_IE(canvas, fileName);
            }
            else {
                $("body").append("<a id='downloadimg' download='" + fileName + "' href='" + canvas.toDataURL("image/png").replace("image/png", "image/octet-stream") + "'><a/>");
            }
            if ($("#downloadimg").length > 0)
                $("#downloadimg")[0].click();

            if($.browser.safari) {// Fix for Chrome
                $(".gm-style>div:first>div").css({
                  left:0,
                  top:0,
                  "transform":transform
                });
            }
        }
    });
}

function download_image_IE(canvas, filename) {
    if ($.browser.version.match(/9.0/)){ //Only for IE9
        var w = window.open();
        $(w.document.body).html('<img src="'+ canvas.toDataURL() +'"/>');
    }
    else{
        var image = canvas.toDataURL();
        image = image.substring(22); // remove data stuff
        var byteString = atob(image);
        var buffer = new ArrayBuffer(byteString.length);
        var intArray = new Uint8Array(buffer);
        for (var i = 0; i < byteString.length; i++) {
            intArray[i] = byteString.charCodeAt(i);
        }
        var blob = new Blob([buffer], { type: "image/png" });
        window.navigator.msSaveOrOpenBlob(blob, filename);
    }
}

Post a Comment for "Save Google Map As An Image - Using Javascript (able To Take Screenshot)"