39

How can I save the current google map as an image? Below is the Javascript I use to initialize the map.

var myMarker = new google.maps.LatLng(result[0].centerLat, result[0].centerLong);
var myOptions = {
  disableDoubleClickZoom: true,
  zoom: result[0].zoom,
  center: myMarker,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

I had a look at https://developers.google.com/maps/documentation/javascript/reference#Map but there seems to be no method that returns a URL or image for the current map object. Is it possible to save the map as an image in some way?

dda
  • 6,030
  • 2
  • 25
  • 34
Atomic Star
  • 5,427
  • 4
  • 39
  • 48

7 Answers7

35

If you want to save more than google maps static API allows (such as custom overlays drawn onto it too complex/large to pass through the querystring), you could export the map container to a canvas using something like html2Canvas (http://html2canvas.hertzen.com/), then convert it to a data URL and do with it as you wish.

function saveMapToDataUrl() {

    var element = $("#mapDiv");

    html2canvas(element, {
        useCORS: true,
        onrendered: function(canvas) {
            var dataUrl= canvas.toDataURL("image/png");

            // DO SOMETHING WITH THE DATAURL
            // Eg. write it to the page
            document.write('<img src="' + dataUrl + '"/>');
        }
    });
}

I believe you need to set the useCORS option to true in order to allow the function to download images from google.

The downside to this approach is it could leave you with about a megabyte of data sitting on your page.

I've tried to use this approach to EXPORT a map to an image to download, but have run into problems in how to get this image to the person in a nice manor. You could use a hyperlink which has it's href attribute set to the dataUrl you created, but the file name cannot be set unless you use HTML attributes like download="filename.png", which has been problematic on different browsers for me. Another approach is to post the dataUrl to the server for the server to then dish out like it needs to, but uploading a large image only to download it again does seem a strange way to handle this.

Arkiliknam
  • 1,805
  • 1
  • 19
  • 35
  • This method worked in Chrome. However Firefox would show the image correctly but continue to load the page and say "connecting". To fix this I changed the document.write statement to window.open(dataUrl); – Aaron Kreider Mar 25 '14 at 16:51
  • 2
    Ouch! A down vote? I wish whoever did that wrote a reason for it! I'm trying to be helpful by providing possible alternate solutions to the question. – Arkiliknam Aug 27 '14 at 15:30
  • 1
    i tried this as well, but the canvas where marker is placed doesn't rendered. tainted canvas may not be exported. – Dariel Pratama Sep 24 '14 at 22:07
  • I would like to use this method for one-off saving of a google maps (png) from Chrome (using Developer console). Would it be possible? If so, how? – msciwoj May 09 '15 at 15:51
  • If you want to save to MySQL DB the field data type must to be enough large. Maybe longtext. – Igor Parra Jun 09 '15 at 07:29
  • This method works great except for IE11 - it adds extra space to the side of the image, equal to the total width of the page minus the image width. I am still looking for a solution for IE11, any ideas? – TetraDev Feb 03 '16 at 20:10
  • I had to create custom logic which divides/splits the image for IE11 in order to prevent it from being the page width. – TetraDev Apr 19 '16 at 17:44
  • thank you very much, the only answer with alternative approach that fits my needs! – Benji Sep 13 '17 at 22:34
23

You can use the google maps static API : https://developers.google.com/maps/documentation/staticmaps/

You can get the parameters that you need to pass to the static maps api (e.g. center , visible region etc) from the google maps javascript api.

basarat
  • 261,912
  • 58
  • 460
  • 511
6

You can use two ways: using html2canvas to generate an image or Google static maps API.

Google static maps API

function mapeado(geocoder, map, infowindow) {
    var staticMapUrl = "https://maps.googleapis.com/maps/api/staticmap";

    //Set the Google Map Center.
    staticMapUrl += "?center=" + document.getElementById('lat').value + "," + document.getElementById('lng').value;

    //Set the Google Map Size.
    staticMapUrl += "&size=640x480&scale=2";

    //Set the Google Map Type.
    staticMapUrl += "&maptype=hybrid";

    //Set the Google Map Zoom.
    staticMapUrl += "&zoom=" + mapOptions.zoom;

    //Loop and add Markers.
    staticMapUrl += "&markers=" + document.getElementById('lat').value + "," + document.getElementById('lng').value;

    //Display the Image of Google Map.
    var imgMap = document.getElementById("imgMap");

    $("#imgMap").attr("src", staticMapUrl);
    return imgMap + "png";
}

html2canvas

function convertasbinaryimage() {
    html2canvas(document.getElementById("map"), {
        useCORS: true,
        onrendered: function (canvas) {
            var img = canvas.toDataURL("image/png");
            img = img.replace('data:image/png;base64,', '');
            var finalImageSrc = 'data:image/png;base64,' + img;
            $('#googlemapbinary').attr('src', finalImageSrc);
         }
    });
}
e0k
  • 6,961
  • 2
  • 23
  • 30
5
function Export() 
{          

 var staticMapUrl = "https://maps.googleapis.com/maps/api/staticmap"; 

        //Set the Google Map Center.        
        staticMapUrl += "?center=" + mapOptions.center.G + "," +     mapOptions.center.K;

        //Set the Google Map Size.
        staticMapUrl += "&size=500x400"; 
        //Set the Google Map Zoom.
        //staticMapUrl += "&zoom=" + mapOptions.zoom;
         staticMapUrl += "&zoom= 19";
          staticMapUrl += "&style=visibility:on";         

          for(var n in polygons)
          {        
           staticMapUrl += "&path=color:0x0x23537C%7Cfillcolor:0x0x23537C|weight:0|"+polygons[n];
          }         

        //Set the Google Map Type.
        staticMapUrl += "&maptype=" + mapOptions.mapTypeId;
        staticMapUrl += "&markers=icon:"+iconpath+"%7c"+latitude+","+longitude;
        staticMapUrl += "&scale= 1";

        for (var j in markers) { 
           if (markers[j]!=='')
           {          
            var image=imagnameewithpath+".png";     
            staticMapUrl += "&markers=icon:"+image+"%7c"+markers[j]+"|";

           }           

      var canvas=document.createElement('canvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();
      imageObj.crossOrigin = "crossOrigin";  // This enables CORS  
      imageObj.onload = function() {
       canvas.width=imageObj.width;
       canvas.height=imageObj.height;
        context.drawImage(imageObj, 0, 0,imageObj.width,imageObj.height);
        var dataurl=canvas.toDataURL('image/png');
         var imgMap = document.getElementById("imgMap");
        imgMap.src = dataurl;        
      };
      imageObj.src = staticMapUrl;

    }
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
Tarun
  • 101
  • 1
  • 4
4

Use the API:

var currentPosition=map.getCenter();
return "http://maps.google.com/maps/api/staticmap?sensor=false&center=" +
  currentPosition.lat() + "," + currentPosition.lng() +
  "&zoom="+map.getZoom()+"&size=512x512&markers=color:green|label:X|" +
  currentPosition.lat() + ',' + currentPosition.lng();
dda
  • 6,030
  • 2
  • 25
  • 34
1

You may find helpful the static maps api, that direct generate images.

https://developers.google.com/maps/documentation/staticmaps/

like that one - this is image:

and there are some tools like : http://gmaps-utility-library-dev.googlecode.com/svn/tags/snapshotcontrol/1.0/examples/optionsWizard.html

ref: Google Maps image?

Community
  • 1
  • 1
Aristos
  • 66,005
  • 16
  • 114
  • 150
1

Here is direct url

For Annotations

https://maps.googleapis.com/maps/api/staticmap?center=23.03,72.58&zoom=6&size=640x400&path=weight:3|color:blue|enc:aofcFz_bhVJ[n@ZpAp@t@b@uA%60FuAzEoCdJiDpLs@VM@y@s@oBcBkAw@cCoAuBu@eEaAiAa@iAi@w@a@o@g@g@k@e@u@uAaCc@i@w@y@eAo@i@UaBc@kAGo@@]JyKA}EC{G?q@?IGKCeGA{CAyCAyEAwEBaFAkJ?yGEyAIiLAiB?{@BcBJ}@@aBGwBEo@A@j@BjBFTHjEl@fOD%60C?|@RARAJERWPL@FE^S%60AI%60A&key=API_KEY

For satellite

https://maps.googleapis.com/maps/api/staticmap?maptype=satellite&center=37.530101,38.600062&zoom=14&size=640x400&key=YOUR_API_KEY

For Styled map

http://maps.googleapis.com/maps/api/staticmap?center=Australia&size=640x400&style=element:labels|visibility:off&style=element:geometry.stroke|visibility:off&style=feature:landscape|element:geometry|saturation:-100&style=feature:water|saturation:-100|invert_lightness:true&key=YOUR_API_KEY

You can directly use this by changing necessary parameters, you just need API_KEY

Mihir Bhatt
  • 3,019
  • 2
  • 37
  • 41