2016-03-02 48 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