Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - Save current Google Map as image

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...