2016-03-02 136 views
1

我必须使用phantomjs制作谷歌地图的屏幕截图。我动态地将一些标记传递给虚拟执行的网页,在地图上绘制它们,然后我拨打map.fitBounds(bounds)以确保地图覆盖所有标记。问题是,我必须知道何时加载map(所有tile?),才能制作屏幕截图。我知道如何通过幻像执行的页面与渲染脚本进行通信,但我不知道如何确保地图已加载。这里是我的代码:如何确保谷歌地图加载?

 map = new google.maps.Map(document.getElementById('map'), { 
     center: { lat: 0.0, lng: 0.0 }, 
     zoom: 8 
     }) 

     showMarkers = function (markers) { 
     markers = markers || [] 
     var bounds = new google.maps.LatLngBounds() 
     for (var i = 0; i < markers.length; ++i) { 
      var marker = new google.maps.Marker({ 
      position: markers[i].position, 
      map: map, 
      title: 'Hello World!' 
      }) 
      bounds.extend(marker.getPosition()) 
     } 
     map.fitBounds(bounds) 

     // for now I set 1 sec timeout, but it is not always enough and I capture gray map with markers (no tiles loaded) 
     setTimeout(function() { 
      console.log('mapReady') 
     }, 1000) 
     } 
+2

看看在http://stackoverflow.com/a/7262773/1149277 –

回答

1

由于@Timur建议“空闲”事件正是我需要的,但我不得不添加一些额外的代码,使其在PhantomJs正常工作:

 var fitBoundsExecuted = false 
     google.maps.event.addListener(map, 'idle', function() { 
      if (!fitBoundsExecuted) { return } 
      fitBoundsExecuted = false 
      setTimeout(function() { 
      console.log('mapReady') 
      }, 1) 
     }) 
     map.fitBounds(bounds) 
     fitBoundsExecuted = true