如何将Google地图导出到包含自定义标记的图片?

时间:2016-06-20 15:50:01

标签: javascript angularjs google-maps google-maps-api-3

根据this answer的建议,我使用html2canvas库将Google地图导出到图片。

我正在研究AngularJS。这是我正在使用的代码:

$scope.shareMap = function(){
        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 + '"/>');
            }
        });
    };

问题是,它不会导出我动态生成的标记。此标记基于AJAX调用的响应生成。

这就是网络上标记的外观: Map with markers, before exporting

这就是它的出口: enter image description here

另外,我注意到如果我在地图上平移,那么&#34; new&#34;显示的区域显示为灰色,如下所示: enter image description here

它似乎只能导出地图首次渲染时显示的内容(只有该特定视口上的地图,没有标记和地图的任何其他区域)。

使用同一个库可以解决我的问题吗?或者你能推荐另一种方法吗?谢谢!

1 个答案:

答案 0 :(得分:3)

PhantomJS这样的工具可以帮助您编写脚本以自动截取网页的屏幕截图(您已使用Google Maps JavaScript API绘制了该网页)。

我有一个使用PhantomJS截取页面截图的小例子。

这是包含一些信息的JavaScript地图:http://jsbin.com/pevizusana/2/edit

<html> 
<head> 
<title>PhantomJS Test</title> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry"></script>
<style type="text/css"> 
  body {
    margin: 0;
  }
  #map {
    width:100%;
    height:100%;
  }
  #loaded {
    display: block;
  }
</style> 
<script type='text/javascript'>

  function initialize() {
    var myLatlng = new google.maps.LatLng(44.65905179951626, 8.3835928124999555);
    var myOptions = {
    zoom: 7,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    var decodedPath = google.maps.geometry.encoding.decodePath('klhrG}nmg@olFmlInT}uJ{mC_tDhjEymNi}@_|GieEnAsGspIihF{pBopBe~Nr`B_xB}sEqhJm`FkeAsfHheDcmE}vI}bCdF_eCclC}iIpu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ItaDroYxiBb]mQ~vKeyD`dBz\\jiKstJzzPiyEfdb@}rG`gA}~AvhFgaBwMg|FzpFk_AhxEyjJwa@_{@ozI{aIlbMigIdyBauF}}MwxD{ZafBs`EkmEvbC_|Cg}Aua@{bU}|D|}@_cBzhFwcGxi@gmBneCeuEgtCazFn`QfuBt}Boe@dmHqyIt{TukDgx@{JthB_aDkkCcuD|mDkoCos@ue@dcM{_I|eAuoCjtD ');

    var setRegion = new google.maps.Polygon({
    path: decodedPath,
    fillColor: "#0000FF",
    fillOpacity: 0.2,
    strokeColor: "#0000FF",
    strokeOpacity: 1.0,
    strokeWeight: 2,      
    map: map
    });

    google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
      document.getElementById("loaded").innerText = "true"; 
    });
}
</script> 
</head> 
<body onload="initialize()"> 
<div id="map"></div>
<div id="loaded"></div>
</body> 
</html>

以下是PhantomJS代码,该代码将截取此网站的屏幕截图:http://pastebin.com/gEXhG1dP

/*
* Captures a webpage with a Google JavaScript Map and exports it to PNG.
*/
//Original code: https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
    start = new Date().getTime(),
    condition = false,
    interval = setInterval(function() {
        if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
            // If not time-out yet and condition not yet fulfilled
            condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
        } else {
            if(!condition) {
                // If condition still not fulfilled (timeout but condition is 'false')
                console.log("'waitFor()' timeout");
                phantom.exit(1);
            } else {
                // Condition fulfilled (timeout and/or condition is 'true')
                console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                clearInterval(interval); //< Stop this interval
            }
        }
    }, 250); //< repeat check every 250ms
};


var page = require('webpage').create();
page.viewportSize = {
  width: 1000,
  height: 1000
};

page.open("http://jsbin.com/pevizusana", function (status) { //Works best on localhost
    // Check for page load success
    if (status !== "success") {
    console.log("Unable to access network");
    } else {
    // Wait for 'signin-dropdown' to be visible
    waitFor(function() {
        // Check in the page if a specific element is now visible
        return page.evaluate(function() {
            return document.getElementById("loaded");
        });
    }, function() {
       console.log("The map should be visible now.");
       page.render('googleScreenShot' + '.png');
       phantom.exit();
    });        
    }
});

结果如下: http://i.imgur.com/Mj951aP.jpg

enter image description here

我希望您觉得此信息有用。